import { useUIStore } from '@/stores/uiStore';
import { useStudentStore } from '@/stores/studentStore';
import { useAttendanceStore } from '@/stores/attendanceStore';
import { useFeeStore } from '@/stores/feeStore';
import { useEquipmentStore } from '@/stores/equipmentStore';
import { useAuthStore } from '@/stores/authStore';
import { StatsCard, SectionTitle, Avatar, StatusBadge } from '@/components/common';
import { formatCurrency, formatCurrencyShort } from '@/lib/formatters';
import { BarChart3, Users, Timer, IndianRupee, Package, UserPlus, ClipboardCheck, Receipt, FileText, PackagePlus, AlertTriangle, TrendingUp, Clock, Star, ChevronRight } from 'lucide-react';
import { Line, Bar } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, LineElement, PointElement, Tooltip, Legend } from 'chart.js';
import { defaultChartOptions, barChartOptions } from '@/lib/chartConfig';

ChartJS.register(CategoryScale, LinearScale, BarElement, LineElement, PointElement, Tooltip, Legend);

export default function AdminDashboard() {
  const { user } = useAuthStore();
  const { navigateTo } = useUIStore();
  const { students } = useStudentStore();
  const { stats: attStats } = useAttendanceStore();
  const { receipts, dueList } = useFeeStore();
  const { items, getLowStockItems } = useEquipmentStore();

  const totalStudents = students.filter(s => s.isActive).length;
  const totalFeesCollected = receipts.reduce((sum, r) => sum + r.amountPaid, 0);
  const totalDues = dueList.reduce((sum, d) => sum + d.amount, 0);
  const equipmentCount = items.length;
  const lowStockItems = getLowStockItems();

  const attendanceData = {
    labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    datasets: [{
      label: 'Present %',
      data: [85, 92, 78, 88, 95, 80],
      backgroundColor: '#F26522',
      borderRadius: 6,
      barThickness: 20,
    }],
  };

  const feeChartData = {
    labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
    datasets: [{
      label: 'Fees Collected',
      data: [4500, 8200, 12300, 15670],
      borderColor: '#F26522',
      backgroundColor: 'rgba(242,101,34,0.1)',
      fill: true,
      tension: 0.4,
      pointRadius: 4,
      pointBackgroundColor: '#F26522',
      pointBorderColor: '#fff',
      pointBorderWidth: 2,
    }],
  };

  const activities = [
    { id: 1, type: 'fee' as const, desc: `Fee received from ${students[0]?.fullName}`, time: '2 min ago' },
    { id: 2, type: 'student' as const, desc: `New student added: ${students[4]?.fullName}`, time: '15 min ago' },
    { id: 3, type: 'timing' as const, desc: `Timing recorded: 500m - ${useStudentStore.getState().students[3]?.fullName}`, time: '30 min ago' },
    { id: 4, type: 'fee' as const, desc: `Due fee reminder sent to ${students[2]?.fullName}`, time: '1 hr ago' },
    { id: 5, type: 'student' as const, desc: 'Batch updated: Evening Batch B', time: '2 hrs ago' },
  ];

  const activityColors: Record<string, string> = { fee: 'bg-emerald-500', student: 'bg-blue-500', timing: 'bg-orange-500', attendance: 'bg-amber-500', equipment: 'bg-red-500' };

  const quickActions = [
    { icon: <UserPlus className="w-5 h-5" />, label: 'Add Student', color: 'text-orange-500', action: () => navigateTo('addStudent') },
    { icon: <ClipboardCheck className="w-5 h-5" />, label: 'Attendance', color: 'text-orange-500', action: () => navigateTo('attendance') },
    { icon: <Timer className="w-5 h-5" />, label: 'Record Time', color: 'text-amber-500', action: () => navigateTo('timing') },
    { icon: <Receipt className="w-5 h-5" />, label: 'Record Fee', color: 'text-emerald-500', action: () => navigateTo('fees') },
    { icon: <FileText className="w-5 h-5" />, label: 'Reports', color: 'text-gray-500', action: () => navigateTo('reports') },
    { icon: <PackagePlus className="w-5 h-5" />, label: 'Equipment', color: 'text-red-500', action: () => navigateTo('equipment') },
  ];

  return (
    <div className="px-4 pt-4 pb-4 space-y-5">
      {/* Summary Card */}
      <div className="brand-gradient rounded-2xl p-5 text-white shadow-lg">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-white/70 text-sm">Welcome back,</p>
            <h2 className="text-xl font-bold">{user?.name || 'Admin'}</h2>
          </div>
          <Avatar name={user?.name || 'Admin'} size="md" />
        </div>
        <div className="grid grid-cols-3 gap-4 mt-5">
          <div className="text-center">
            <Users className="w-5 h-5 mx-auto text-white/70" />
            <p className="text-2xl font-bold mt-1">{totalStudents}</p>
            <p className="text-[10px] text-white/60">Students</p>
          </div>
          <div className="text-center">
            <ClipboardCheck className="w-5 h-5 mx-auto text-white/70" />
            <p className="text-2xl font-bold mt-1">{attStats.percentage}%</p>
            <p className="text-[10px] text-white/60">Attendance</p>
          </div>
          <div className="text-center">
            <IndianRupee className="w-5 h-5 mx-auto text-white/70" />
            <p className="text-2xl font-bold mt-1">{formatCurrencyShort(totalFeesCollected)}</p>
            <p className="text-[10px] text-white/60">Fees This Month</p>
          </div>
        </div>
      </div>

      {/* Stats Row */}
      <div className="grid grid-cols-2 gap-3">
        <StatsCard icon={<Users className="w-5 h-5 text-orange-500" />} label="Total Students" value={totalStudents} trend="12%" trendUp />
        <StatsCard icon={<IndianRupee className="w-5 h-5 text-emerald-500" />} label="Fees Collected" value={formatCurrencyShort(totalFeesCollected)} subtitle="this month" />
        <StatsCard icon={<AlertTriangle className="w-5 h-5 text-red-500" />} label="Pending Dues" value={formatCurrencyShort(totalDues)} trend="3 students" trendUp={false} />
        <StatsCard icon={<Package className="w-5 h-5 text-gray-500" />} label="Equipment" value={`${equipmentCount} items`} subtitle={`${lowStockItems.length} low stock`} />
      </div>

      {/* Charts */}
      <div className="bg-white rounded-2xl p-4 card-shadow">
        <SectionTitle title="Attendance Trend" action={<span className="text-xs text-orange-500 font-medium">This Week</span>} />
        <div className="h-44">
          <Bar data={attendanceData} options={barChartOptions} />
        </div>
      </div>

      <div className="bg-white rounded-2xl p-4 card-shadow">
        <SectionTitle title="Fee Collection" action={<span className="text-xs text-orange-500 font-medium">This Month</span>} />
        <div className="h-40">
          <Line data={feeChartData} options={defaultChartOptions} />
        </div>
      </div>

      {/* Quick Actions */}
      <div>
        <SectionTitle title="Quick Actions" />
        <div className="grid grid-cols-3 gap-3">
          {quickActions.map((action, i) => (
            <button key={i} onClick={action.action} className="bg-white rounded-xl p-3 card-shadow flex flex-col items-center gap-1.5 active:scale-95 transition-transform">
              <span className={action.color}>{action.icon}</span>
              <span className="text-[10px] font-medium text-gray-700 text-center leading-tight">{action.label}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Recent Activity */}
      <div>
        <SectionTitle title="Recent Activity" action={<button className="text-xs text-orange-500 font-medium">View All</button>} />
        <div className="bg-white rounded-2xl card-shadow divide-y divide-gray-50">
          {activities.map(a => (
            <div key={a.id} className="flex items-center gap-3 px-4 py-3">
              <div className={`w-2 h-2 rounded-full ${activityColors[a.type]} flex-shrink-0`} />
              <p className="flex-1 text-sm text-gray-700 truncate">{a.desc}</p>
              <span className="text-[10px] text-gray-400 flex-shrink-0">{a.time}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Low Stock Alert */}
      {lowStockItems.length > 0 && (
        <div className="bg-amber-50 border-l-4 border-amber-400 rounded-r-xl p-4 flex items-center gap-3">
          <AlertTriangle className="w-5 h-5 text-amber-500 flex-shrink-0" />
          <div className="flex-1">
            <p className="text-sm font-medium text-gray-800">{lowStockItems.length} equipment items running low</p>
          </div>
          <button onClick={() => navigateTo('equipment')} className="text-xs font-semibold text-orange-500">Check</button>
        </div>
      )}

      {/* Upcoming Birthdays */}
      <div>
        <SectionTitle title="Upcoming Birthdays" action={<span className="text-[10px] bg-red-500 text-white px-2 py-0.5 rounded-full font-medium">2 this month</span>} />
        <div className="flex gap-3 overflow-x-auto no-scrollbar pb-1">
          {students.slice(0, 4).map(s => (
            <button key={s.id} onClick={() => { useStudentStore.getState().selectStudent(s.id); navigateTo('studentDetail'); }}
              className="bg-white rounded-xl p-3 card-shadow flex flex-col items-center min-w-[100px] active:scale-95 transition-transform">
              <Avatar name={s.fullName} size="md" />
              <p className="text-[11px] font-semibold text-gray-800 mt-2 text-center truncate w-full">{s.fullName.split(' ')[0]}</p>
              <p className="text-[10px] text-gray-400">{s.dateOfBirth ? new Date(s.dateOfBirth).toLocaleDateString('en-IN', { day: 'numeric', month: 'short' }) : ''}</p>
              <p className="text-[10px] text-orange-500 font-medium">Turning {s.age}</p>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}
