import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import api, { useAuthStore } from '../../store/auth';
import { Avatar } from '../../components/Avatar';
import {
  Users, GraduationCap, BookOpen, DollarSign,
  Calendar, MessageSquare, Settings, TrendingUp,
  Plus, Bell, Search, HelpCircle, ArrowRight,
  CheckCircle2, AlertCircle, Clock, UserPlus
} from 'lucide-react';

export default function AdminDashboard() {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const [stats, setStats] = useState<any>(null);
  const [recentActivity, setRecentActivity] = useState<any[]>([]);
  const [enrollmentByClass, setEnrollmentByClass] = useState<any[]>([]);
  const [topDebtors, setTopDebtors] = useState<any[]>([]);
  const [totalDebtors, setTotalDebtors] = useState<number>(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Quick action tile -> inferred route
  const actionRoutes: Record<string, string> = {
    'Add Student': '/users',
    'Mark Attendance': '/attendance',
    'Process Fees': '/fees',
    'Send Alert': '/messages',
    'New Report': '/reports',
    'System Logs': '/audit-logs',
  };

  useEffect(() => {
    setLoading(true);
    Promise.all([
      api.get('/dashboard/admin'),
      api.get('/fees/students'),
    ]).then(([dashRes, feesRes]) => {
      setStats(dashRes.data.stats);
      setRecentActivity(dashRes.data.recentActivity || []);
      setEnrollmentByClass(dashRes.data.enrollmentByClass || []);
      const rows = (feesRes.data || []).map((sf: any) => ({
        id: sf.student_id,
        first_name: sf.first_name,
        last_name: sf.last_name,
        outstanding: (Number(sf.amount) || 0) - (Number(sf.paid_amount) || 0),
      })).filter((sf: any) => sf.outstanding > 0);
      const byStudent = new Map<number, any>();
      rows.forEach((r: any) => {
        const prev = byStudent.get(r.id);
        if (!prev || r.outstanding > prev.outstanding) byStudent.set(r.id, r);
      });
      const distinct = Array.from(byStudent.values()).sort((a: any, b: any) => b.outstanding - a.outstanding);
      setTopDebtors(distinct.slice(0, 4));
      setTotalDebtors(distinct.length);
      setError(null);
    }).catch(err => {
      console.error('Failed to load admin dashboard:', err);
      setError(err?.response?.data?.error || 'Failed to load dashboard');
    }).finally(() => setLoading(false));
  }, []);

  if (loading) return (
    <div className="flex flex-col justify-center items-center h-[60vh] gap-4">
      <div className="w-12 h-12 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
      <p className="text-text-muted font-medium animate-pulse">Loading NextGen Dashboard...</p>
    </div>
  );

  if (error || !stats) return (
    <div className="flex flex-col justify-center items-center h-[60vh] gap-4">
      <AlertCircle size={48} className="text-red-500" />
      <p className="text-text-muted font-medium">Unable to load dashboard data.</p>
      <p className="text-sm text-text-muted">{error}</p>
      <button onClick={() => window.location.reload()} className="px-4 py-2 bg-primary text-white rounded-xl">Retry</button>
    </div>
  );

  const cards = [
    { label: 'Students', value: stats.totalStudents, icon: GraduationCap, trend: '+', subtext: 'Total active enrollment', color: 'blue', path: '/users' },
    { label: 'Teachers', value: stats.totalTeachers, icon: Users, trend: '+', subtext: 'Faculty members', color: 'indigo', path: '/users' },
    { label: 'Classes', value: stats.totalClasses, icon: BookOpen, trend: '+', subtext: 'Active sessions today', color: 'emerald', path: '/classes' },
    { label: 'Revenue', value: `$${stats.totalRevenue.toLocaleString()}`, icon: DollarSign, trend: '+', subtext: 'Net monthly income', color: 'primary', highlight: true, path: '/fees' },
  ];

  return (
    <div className="space-y-8 animate-in fade-in duration-500">
      {/* Header Section */}
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-text tracking-tight">Welcome back, {user?.first_name || 'Admin'}!</h1>
          <p className="text-text-muted mt-1 text-lg">Here is what's happening at NextGen Learning today.</p>
        </div>
        <button onClick={() => navigate('/users')} className="flex items-center gap-2 bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-xl font-semibold transition-all shadow-lg shadow-blue-900/10 active:scale-[0.98]">
          <Plus size={20} />
          <span>Add New Entry</span>
        </button>
      </div>

      {/* Bento Stats Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {cards.map((card) => (
          <div
            key={card.label}
            onClick={() => navigate(card.path)}
            className={`p-6 rounded-2xl border transition-all duration-300 hover:shadow-md group cursor-pointer ${card.highlight ? 'bg-slate-900 border-transparent text-white ring-4 ring-blue-500/5' : 'bg-card border-border'}`}
          >
            <div className="flex justify-between items-start mb-4">
              <div className={`p-2.5 rounded-xl ${card.highlight ? 'bg-white/10 text-white' : 'bg-muted text-[#0047AB]'}`}>
                <card.icon size={22} />
              </div>
              <div className={`flex items-center gap-1 text-[0.7rem] font-bold px-2 py-1 rounded-full ${card.highlight ? 'bg-emerald-500/20 text-emerald-400' : 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400'}`}>
                <TrendingUp size={12} />
                {card.trend}
              </div>
            </div>
            <p className={`text-xs font-bold uppercase tracking-wider ${card.highlight ? 'text-white/60' : 'text-text-muted'}`}>
              {card.label}
            </p>
            <h3 className="text-3xl font-black mt-1 tracking-tight">{card.value}</h3>
            <p className={`text-[0.65rem] mt-2 italic font-medium ${card.highlight ? 'text-white/40' : 'text-text-muted'}`}>
              {card.subtext}
            </p>
          </div>
        ))}
      </div>

      {/* Main Content Layout */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Column (2/3) */}
        <div className="lg:col-span-2 space-y-6">
          {/* Academic Vitality Card */}
          <div className="bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
            <div className="px-6 py-4 border-b border-border flex justify-between items-center bg-muted/50">
              <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">Academic Vitality</h4>
              <span className="text-[0.7rem] font-bold text-text-muted">{new Date().toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })}</span>
            </div>
            <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-8">
              {/* Attendance Widget */}
              <div className="space-y-4 cursor-pointer hover:opacity-80 transition-opacity" onClick={() => navigate('/attendance')}>
                <div className="flex justify-between items-end">
                  <div>
                    <p className="text-[0.6rem] text-text-muted uppercase font-black tracking-widest">Today's Attendance</p>
                    <h5 className="text-xl font-bold text-text">
                      {stats.todayAttendance.total > 0 ? Math.round((stats.todayAttendance.present / stats.todayAttendance.total) * 100) : 0}% Present
                    </h5>
                  </div>
                  <span className="text-[0.65rem] text-emerald-600 dark:text-emerald-400 bg-emerald-50 dark:bg-emerald-900/20 px-2.5 py-1 rounded-full border border-emerald-100 dark:border-emerald-900/30 font-bold uppercase tracking-tight">On Track</span>
                </div>
                <div className="w-full bg-muted rounded-full h-3.5 overflow-hidden p-0.5 border border-border shadow-inner">
                  <div
                    className="bg-primary h-full rounded-full transition-all duration-1000 relative overflow-hidden"
                    style={{ width: `${stats.todayAttendance.total > 0 ? (stats.todayAttendance.present / stats.todayAttendance.total) * 100 : 0}%` }}
                  >
                    <div className="absolute inset-0 bg-white/20 animate-pulse"></div>
                  </div>
                </div>
                <p className="text-xs text-text-muted font-medium leading-relaxed">
                  {stats.todayAttendance.present}/{stats.todayAttendance.total} students checked in today.
                </p>
              </div>

              {/* Pending Fees Widget */}
              <div className="space-y-4 bg-orange-50/30 dark:bg-orange-950/20 p-5 rounded-2xl border border-orange-100/50 dark:border-orange-900/20 cursor-pointer hover:opacity-80 transition-opacity" onClick={() => navigate('/fees')}>
                <div>
                  <p className="text-[0.6rem] text-orange-600/70 dark:text-orange-400/70 uppercase font-black tracking-widest">Pending Fees</p>
                  <h5 className="text-xl font-bold text-orange-900 dark:text-orange-100">${stats.pendingFees.toLocaleString()}</h5>
                </div>
                <div className="flex -space-x-2">
                  {topDebtors.map((td) => (
                    <div key={td.id} className="w-8 h-8 rounded-full border-2 border-border bg-muted flex items-center justify-center text-[0.6rem] font-bold text-text-muted shadow-sm overflow-hidden">
                      <Avatar firstName={td.first_name} lastName={td.last_name} />
                    </div>
                  ))}
                  {(topDebtors.length === 0 || totalDebtors > topDebtors.length) && (
                    <div className="w-8 h-8 rounded-full border-2 border-border bg-orange-100 dark:bg-orange-900 flex items-center justify-center text-[0.6rem] font-black text-orange-600 dark:text-orange-400 shadow-sm">
                      +{topDebtors.length === 0 ? totalDebtors : Math.max(0, totalDebtors - topDebtors.length)}
                    </div>
                  )}
                </div>
                <p className="text-xs text-orange-800/70 dark:text-orange-200/70 font-medium">Outstanding balances across the student body.</p>
              </div>
            </div>
          </div>

          {/* Recent Activity Table */}
          <div className="bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
            <div className="px-6 py-4 border-b border-border flex justify-between items-center bg-muted/50">
              <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">Recent Activity</h4>
              <button onClick={() => navigate('/audit-logs')} className="text-primary text-[0.7rem] font-bold hover:underline">View All Activity</button>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-left">
                <thead className="bg-muted/80 border-b border-border">
                  <tr>
                    <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Entity</th>
                    <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Action</th>
                    <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Time</th>
                    <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {recentActivity.length > 0 ? recentActivity.map((activity: any, idx: number) => (
                    <tr key={idx} className="hover:bg-muted transition-colors group">
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-3">
                          <div className={`w-9 h-9 rounded-xl flex items-center justify-center font-bold text-xs ${activity.bgColor} ${activity.textColor} shadow-sm group-hover:scale-105 transition-transform`}>
                            {activity.initial}
                          </div>
                          <div>
                            <p className="text-[0.85rem] font-bold text-text">{activity.entity}</p>
                            <p className="text-[0.65rem] text-text-muted font-medium">{activity.id}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <span className="text-[0.8rem] font-medium text-text-secondary">{activity.action}</span>
                      </td>
                      <td className="px-6 py-4">
                        <span className="text-[0.75rem] text-text-muted font-mono">{activity.time}</span>
                      </td>
                      <td className="px-6 py-4">
                        <span className={`px-2.5 py-1 rounded-lg text-[0.6rem] font-black tracking-tighter ${activity.bgColor} ${activity.textColor}`}>
                          {activity.status}
                        </span>
                      </td>
                    </tr>
                  )) : (
                    <tr>
                      <td colSpan={4} className="px-6 py-8 text-center text-text-muted text-sm">
                        No recent activity to display.
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>

          {/* Enrollment by Class (real data) */}
          {enrollmentByClass.length > 0 && (
            <div className="bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
              <div className="px-6 py-4 border-b border-border bg-muted/50 flex justify-between items-center">
                <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">Enrollment by Class</h4>
                <button onClick={() => navigate('/enrollments')} className="text-[0.65rem] font-black uppercase tracking-widest text-primary hover:underline">Manage All →</button>
              </div>
              <div className="p-6 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
                {enrollmentByClass.map((c: any, i: number) => (
                  <div key={i} onClick={() => navigate('/enrollments')} className="p-4 bg-muted/50 hover:bg-primary/5 hover:border-primary/30 transition-all rounded-xl border border-border cursor-pointer">
                    <p className="text-[0.65rem] font-black uppercase text-text-muted tracking-widest">{c.name} {c.section}</p>
                    <p className="text-2xl font-black text-text">{c.count} <span className="text-[0.65rem] font-medium text-text-muted">students</span></p>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Right Column (1/3) */}
        <div className="space-y-6">
          {/* Quick Actions Panel */}
          <div className="bg-card rounded-2xl border border-border p-6 shadow-sm">
            <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary mb-6">Quick Actions</h4>
            <div className="grid grid-cols-2 gap-3">
              {[
                { label: 'Enrollments', icon: UserPlus, color: 'blue', path: '/enrollments' },
                { label: 'Add Student', icon: Plus, color: 'blue', path: '/users' },
                { label: 'Mark Attendance', icon: CheckCircle2, color: 'emerald', path: '/attendance' },
                { label: 'Process Fees', icon: DollarSign, color: 'orange', path: '/fees' },
                { label: 'Send Alert', icon: Bell, color: 'purple', path: '/notice-board' },
                { label: 'New Report', icon: TrendingUp, color: 'indigo', path: '/reports' },
                { label: 'System Logs', icon: Clock, color: 'slate', path: '/audit-logs' },
              ].map((action) => (
                <button
                  key={action.label}
                  onClick={() => navigate(action.path)}
                  className="flex flex-col items-center justify-center p-4 bg-muted/50 hover:bg-primary hover:text-white rounded-2xl transition-all duration-300 group border border-border hover:border-transparent hover:shadow-lg hover:shadow-blue-900/10"
                >
                  <div className="mb-2 p-2 rounded-xl group-hover:bg-white/10 transition-colors">
                    <action.icon size={20} />
                  </div>
                  <span className="text-[0.7rem] font-bold text-center leading-tight">{action.label}</span>
                </button>
              ))}
            </div>
            <button onClick={() => navigate('/settings')} className="w-full mt-6 py-3 px-4 bg-muted hover:bg-muted/80 text-text font-bold text-[0.75rem] rounded-xl transition-all flex items-center justify-center gap-2 border border-border">
              Explore All Modules
              <ArrowRight size={16} />
            </button>
          </div>

          {/* System Status Panel */}
          <div className="bg-slate-900 rounded-2xl p-6 text-white shadow-xl shadow-blue-900/10 relative overflow-hidden">
            <div className="absolute -right-8 -bottom-8 opacity-10">
              <Settings size={120} />
            </div>
            <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-white/40 mb-4 relative z-10">Infrastructure</h4>
            <div className="space-y-3 relative z-10">
              {[
                { label: 'Main Database', status: 'Healthy', color: 'bg-emerald-400' },
                { label: 'API Endpoint', status: 'Stable', color: 'bg-emerald-400' },
                { label: 'Auth Service', status: 'Online', color: 'bg-emerald-400' },
                { label: 'Sync Engine', status: 'Active', color: 'bg-emerald-400' },
              ].map((item) => (
                <div key={item.label} className="flex items-center justify-between p-3 bg-white/5 rounded-xl border border-white/5 backdrop-blur-sm">
                  <div className="flex items-center gap-3">
                    <div className={`w-2 h-2 rounded-full ${item.color} animate-pulse`} />
                    <span className="text-xs font-semibold text-white/80">{item.label}</span>
                  </div>
                  <span className="text-[0.6rem] font-black text-white/40 uppercase">{item.status}</span>
                </div>
              ))}
            </div>
            <div className="mt-6 pt-4 border-t border-white/10 flex items-center justify-between text-[0.65rem]">
              <span className="text-white/40">Core Version 2.4.0-pro</span>
              <div className="flex items-center gap-2 text-emerald-400 font-bold">
                <CheckCircle2 size={12} />
                <span>ALL SYSTEMS OPTIMAL</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
