'use client';
import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import { Plus, Search, RefreshCw, BookOpen, Users, TrendingUp, FileText, X, ChevronDown, Trash2 } from 'lucide-react';
import toast from 'react-hot-toast';
import ClientCard from './ClientCard';
import StatsCard from './StatsCard';
import LoadingSpinner from './LoadingSpinner';
import MobileBottomNav from './mobile/MobileBottomNav';
import OfflineBanner from './mobile/OfflineBanner';
import { SkeletonClientCard, SkeletonStatsCard } from './mobile/SkeletonCard';
import { clients as clientsApi, analytics as analyticsApi, type Client, type User, type Analytics } from '@/utils/api';
import { formatWordCount } from '@/utils/analytics';

const SPORTS = ['baseball', 'football', 'basketball', 'cricket', 'boxing', 'athletics', 'tennis', 'soccer'];

interface Props { user: User; onLogout: () => void; }

export default function Dashboard({ user, onLogout }: Props) {
  const router = useRouter();
  const [clientList, setClientList] = useState<Client[]>([]);
  const [allClients, setAllClients] = useState<Client[]>([]);
  const [stats, setStats] = useState<Analytics | null>(null);
  const [activeTab, setActiveTab] = useState('home');
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [search, setSearch] = useState('');
  const [filter, setFilter] = useState('all');
  const [showAddModal, setShowAddModal] = useState(false);
  const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);
  const [addForm, setAddForm] = useState({ name: '', email: '', bookTitle: '', sport: 'baseball' });
  const [addLoading, setAddLoading] = useState(false);

  const loadData = useCallback(async (silent = false) => {
    if (!silent) setLoading(true);
    else setRefreshing(true);
    try {
      const [clientsRes, statsData] = await Promise.all([
        clientsApi.list(),
        analyticsApi.get(),
      ]);
      setStats(statsData);
      setAllClients(clientsRes.clients);
    } catch (err: any) {
      toast.error(err.message || 'Failed to load data');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, []); // no deps — filter/search applied client-side after fetch

  // Re-filter when search or filter changes without re-fetching
  useEffect(() => { loadData(); }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // Client-side filter whenever allClients, filter, or search changes
  useEffect(() => {
    let result = allClients;
    if (filter !== 'all') result = result.filter(c => c.status === filter);
    if (search.trim()) {
      const q = search.toLowerCase();
      result = result.filter(c =>
        c.name.toLowerCase().includes(q) || c.bookTitle.toLowerCase().includes(q)
      );
    }
    setClientList(result);
  }, [allClients, filter, search]);

  const handleAddClient = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!addForm.name || !addForm.email || !addForm.bookTitle) {
      toast.error('Please fill in all fields'); return;
    }
    setAddLoading(true);
    try {
      await clientsApi.create(addForm);
      toast.success(`${addForm.name} added successfully!`);
      setShowAddModal(false);
      setAddForm({ name: '', email: '', bookTitle: '', sport: 'baseball' });
      loadData(true);
    } catch (err: any) {
      // Show specific duplicate error with option to view existing
      if (err.message?.includes('already exists')) {
        toast.error(err.message, { duration: 5000 });
      } else {
        toast.error(err.message || 'Failed to add client');
      }
    } finally {
      setAddLoading(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await clientsApi.delete(id);
      toast.success('Client deleted');
      setDeleteConfirm(null);
      loadData(true);
    } catch (err: any) {
      toast.error(err.message || 'Failed to delete');
    }
  };

  const handleReset = async (id: string) => {
    if (!confirm('Reset this interview? All messages will be cleared but the client will remain.')) return;
    try {
      await clientsApi.reset(id);
      toast.success('Interview reset successfully');
      loadData(true);
    } catch (err: any) {
      toast.error(err.message || 'Failed to reset');
    }
  };

  const handleRegenerateLink = async (client: Client) => {
    try {
      const res = await clientsApi.regenerateLink(client.id);
      toast.success('New link generated!');
      navigator.clipboard.writeText(`${window.location.origin}/interview/link/${res.uniqueLink}`);
      toast('New link copied to clipboard', { icon: '📋' });
      loadData(true);
    } catch (err: any) {
      toast.error(err.message || 'Failed to regenerate link');
    }
  };

  const handleCopyLink = (client: Client) => {
    const link = `${window.location.origin}/interview/link/${client.uniqueLink}`;
    navigator.clipboard.writeText(link);
    toast.success('Interview link copied!');
  };

  return (
    <div className="min-h-screen has-bottom-nav lg:pb-0" style={{ background: 'var(--bg-secondary)' }}>
      <OfflineBanner />
      {/* Header */}
      <header className="sticky top-0 z-40 border-b" style={{ background: 'var(--bg-card)', borderColor: 'var(--border)' }}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 h-16 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 rounded-xl flex items-center justify-center"
              style={{ background: 'linear-gradient(135deg, #6366f1, #a855f7)' }}>
              <BookOpen className="w-5 h-5 text-white" />
            </div>
            <span className="font-bold text-lg gradient-text">Muse Pro</span>
          </div>
          <div className="flex items-center gap-3">
            <div className="hidden sm:flex items-center gap-2 text-sm" style={{ color: 'var(--text-secondary)' }}>
              <div className="w-7 h-7 rounded-full flex items-center justify-center text-white text-xs font-bold"
                style={{ background: 'linear-gradient(135deg, #6366f1, #a855f7)' }}>
                {user.name[0].toUpperCase()}
              </div>
              <span>{user.name}</span>
            </div>
            <button onClick={onLogout} className="btn-ghost text-xs">Sign out</button>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 sm:px-6 py-8">
        {/* Stats */}
        {stats ? (
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
            <StatsCard label="Total Clients"     value={stats.total}                    icon={Users}      color="#6366f1" delay={0}    />
            <StatsCard label="Active Interviews" value={stats.active}                   icon={TrendingUp} color="#a855f7" delay={0.05} />
            <StatsCard label="Books Completed"   value={stats.completed}                icon={BookOpen}   color="#10b981" delay={0.1}  />
            <StatsCard label="Total Words"       value={formatWordCount(stats.totalWords)} icon={FileText} color="#f59e0b" delay={0.15} />
          </div>
        ) : (
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
            {[1,2,3,4].map(i => <SkeletonStatsCard key={i} />)}
          </div>
        )}

        {/* Toolbar */}
        <div className="flex flex-col sm:flex-row gap-3 mb-6">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4" style={{ color: 'var(--text-secondary)' }} />
            <input
              type="text" placeholder="Search clients..." value={search}
              onChange={e => setSearch(e.target.value)}
              className="input-field pl-9" />
          </div>
          <div className="flex gap-2">
            {['all', 'active', 'completed', 'pending'].map(f => (
              <button key={f} onClick={() => setFilter(f)}
                className="px-3 py-2 rounded-lg text-xs font-semibold capitalize transition-all"
                style={filter === f
                  ? { background: 'linear-gradient(135deg, #6366f1, #a855f7)', color: 'white' }
                  : { background: 'var(--bg-card)', color: 'var(--text-secondary)', border: '1px solid var(--border)' }}>
                {f}
              </button>
            ))}
          </div>
          <button onClick={() => loadData(true)} disabled={refreshing}
            className="btn-secondary flex items-center gap-2 px-3">
            <RefreshCw className={`w-4 h-4 ${refreshing ? 'animate-spin' : ''}`} />
          </button>
          <button onClick={() => setShowAddModal(true)} className="btn-primary flex items-center gap-2">
            <Plus className="w-4 h-4" /> Add Client
          </button>
        </div>

        {/* Client Grid */}
        {loading ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {[1,2,3,4,5,6].map(i => <SkeletonClientCard key={i} />)}
          </div>
        ) : clientList.length === 0 ? (
          <div className="text-center py-20">
            <div className="w-16 h-16 rounded-2xl mx-auto mb-4 flex items-center justify-center"
              style={{ background: 'rgba(99,102,241,0.1)' }}>
              <Users className="w-8 h-8" style={{ color: '#6366f1' }} />
            </div>
            <p className="font-semibold mb-1" style={{ color: 'var(--text-primary)' }}>No clients yet</p>
            <p className="text-sm mb-4" style={{ color: 'var(--text-secondary)' }}>Add your first athlete to get started</p>
            <button onClick={() => setShowAddModal(true)} className="btn-primary">
              <Plus className="w-4 h-4 inline mr-1" /> Add Client
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {clientList.map((c, i) => (
              <ClientCard
                key={c.id} client={c} index={i}
                onInterview={() => router.push(`/interview/${c.id}`)}
                onCopyLink={() => handleCopyLink(c)}
                onDelete={() => setDeleteConfirm(c.id)}
                onViewBook={() => router.push(`/book/${c.id}`)}
                onReset={() => handleReset(c.id)}
                onRegenerateLink={() => handleRegenerateLink(c)}
              />
            ))}
          </div>
        )}
      </main>

      {/* Add Client Modal */}
      <AnimatePresence>
        {showAddModal && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center p-4"
            style={{ background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(4px)' }}
            onClick={e => e.target === e.currentTarget && setShowAddModal(false)}>
            <motion.div initial={{ scale: 0.95, opacity: 0 }} animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.95, opacity: 0 }}
              className="card w-full max-w-md p-6" style={{ background: 'var(--bg-card)' }}>
              <div className="flex items-center justify-between mb-5">
                <h2 className="font-bold text-lg" style={{ color: 'var(--text-primary)' }}>Add New Client</h2>
                <button onClick={() => setShowAddModal(false)} className="btn-ghost p-1.5 rounded-lg">
                  <X className="w-4 h-4" />
                </button>
              </div>
              <form onSubmit={handleAddClient} className="space-y-4">
                <div>
                  <label className="block text-xs font-medium mb-1.5" style={{ color: 'var(--text-secondary)' }}>Athlete Name</label>
                  <input type="text" placeholder="e.g. Michael Jordan" value={addForm.name}
                    onChange={e => setAddForm(f => ({ ...f, name: e.target.value }))} className="input-field" />
                </div>
                <div>
                  <label className="block text-xs font-medium mb-1.5" style={{ color: 'var(--text-secondary)' }}>Email</label>
                  <input type="email" placeholder="athlete@email.com" value={addForm.email}
                    onChange={e => setAddForm(f => ({ ...f, email: e.target.value }))} className="input-field" />
                </div>
                <div>
                  <label className="block text-xs font-medium mb-1.5" style={{ color: 'var(--text-secondary)' }}>Book Title</label>
                  <input type="text" placeholder="e.g. The Last Dance" value={addForm.bookTitle}
                    onChange={e => setAddForm(f => ({ ...f, bookTitle: e.target.value }))} className="input-field" />
                </div>
                <div>
                  <label className="block text-xs font-medium mb-1.5" style={{ color: 'var(--text-secondary)' }}>Sport</label>
                  <div className="relative">
                    <select value={addForm.sport}
                      onChange={e => setAddForm(f => ({ ...f, sport: e.target.value }))}
                      className="input-field appearance-none pr-8 capitalize">
                      {SPORTS.map(s => <option key={s} value={s}>{s}</option>)}
                    </select>
                    <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 pointer-events-none"
                      style={{ color: 'var(--text-secondary)' }} />
                  </div>
                </div>
                <div className="flex gap-3 pt-2">
                  <button type="button" onClick={() => setShowAddModal(false)} className="btn-secondary flex-1">Cancel</button>
                  <button type="submit" disabled={addLoading} className="btn-primary flex-1">
                    {addLoading ? <LoadingSpinner size="sm" /> : 'Add Client'}
                  </button>
                </div>
              </form>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Delete Confirm Modal */}
      <AnimatePresence>
        {deleteConfirm && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center p-4"
            style={{ background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(4px)' }}>
            <motion.div initial={{ scale: 0.95 }} animate={{ scale: 1 }} exit={{ scale: 0.95 }}
              className="card w-full max-w-sm p-6 text-center" style={{ background: 'var(--bg-card)' }}>
              <div className="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center mx-auto mb-4">
                <Trash2 className="w-6 h-6 text-red-500" />
              </div>
              <h3 className="font-bold mb-2" style={{ color: 'var(--text-primary)' }}>Delete Client?</h3>
              <p className="text-sm mb-5" style={{ color: 'var(--text-secondary)' }}>
                This will permanently delete the client and all interview data.
              </p>
              <div className="flex gap-3">
                <button onClick={() => setDeleteConfirm(null)} className="btn-secondary flex-1">Cancel</button>
                <button onClick={() => handleDelete(deleteConfirm)}
                  className="flex-1 py-2.5 rounded-xl font-semibold text-sm text-white bg-red-500 hover:bg-red-600 transition-colors">
                  Delete
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      <MobileBottomNav activeTab={activeTab} onTabChange={setActiveTab} />
    </div>
  );
}


