import { useAuthStore } from '@/stores/authStore';
import { useUIStore } from '@/stores/uiStore';
import { useStudentStore } from '@/stores/studentStore';
import { useAttendanceStore } from '@/stores/attendanceStore';
import { useTimingStore } from '@/stores/timingStore';
import { Avatar, StatsCard, SectionTitle } from '@/components/common';
import { BarChart3, Users, Timer, ClipboardCheck, BookOpen } from 'lucide-react';
import { Bar } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Tooltip } from 'chart.js';
import { barChartOptions } from '@/lib/chartConfig';

ChartJS.register(CategoryScale, LinearScale, BarElement, Tooltip);

export default function AssistantDashboard() {
  const { user } = useAuthStore();
  const { navigateTo } = useUIStore();
  const { students } = useStudentStore();
  const { stats: attStats } = useAttendanceStore();
  const { records: timingRecords } = useTimingStore();

  const activeStudents = students.filter(s => s.isActive);
  const todayRecords = timingRecords.slice(0, 3);

  const batches = [
    { name: 'Morning Batch A', time: '6:00 AM', count: 3 },
    { name: 'Evening Batch B', time: '4:00 PM', count: 3 },
  ];

  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,
    }],
  };

  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">Good day,</p>
            <h2 className="text-xl font-bold">{user?.name || 'Coach'}</h2>
          </div>
          <Avatar name={user?.name || 'Coach'} size="md" />
        </div>
        <div className="grid grid-cols-3 gap-4 mt-5">
          <div className="text-center">
            <BookOpen className="w-5 h-5 mx-auto text-white/70" />
            <p className="text-2xl font-bold mt-1">2</p>
            <p className="text-[10px] text-white/60">My Batches</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">
            <Timer className="w-5 h-5 mx-auto text-white/70" />
            <p className="text-2xl font-bold mt-1">{todayRecords.length}</p>
            <p className="text-[10px] text-white/60">Timings Today</p>
          </div>
        </div>
      </div>

      {/* Stats Row */}
      <div className="grid grid-cols-3 gap-3">
        <StatsCard icon={<BookOpen className="w-5 h-5 text-orange-500" />} label="My Batches" value="2" />
        <StatsCard icon={<Users className="w-5 h-5 text-emerald-500" />} label="Today's Attendance" value={`${attStats.percentage}%`} />
        <StatsCard icon={<Timer className="w-5 h-5 text-amber-500" />} label="Timings Today" value={`${todayRecords.length}`} />
      </div>

      {/* Attendance Chart */}
      <div className="bg-white rounded-2xl p-4 card-shadow">
        <SectionTitle title="Attendance Trend" />
        <div className="h-44">
          <Bar data={attendanceData} options={barChartOptions} />
        </div>
      </div>

      {/* My Batches */}
      <div>
        <SectionTitle title="My Batches Today" />
        <div className="space-y-2">
          {batches.map((batch, i) => (
            <button key={i} onClick={() => navigateTo('attendance')}
              className="w-full bg-white rounded-xl p-4 card-shadow flex items-center justify-between text-left active:scale-[0.98] transition-transform">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-orange-50 rounded-xl flex items-center justify-center">
                  <BookOpen className="w-5 h-5 text-orange-500" />
                </div>
                <div>
                  <p className="text-sm font-semibold text-gray-900">{batch.name}</p>
                  <p className="text-xs text-gray-400">{batch.time}</p>
                </div>
              </div>
              <span className="px-2.5 py-1 bg-orange-100 text-orange-600 text-xs font-semibold rounded-full">{batch.count} students</span>
            </button>
          ))}
        </div>
      </div>

      {/* Quick Actions */}
      <div>
        <SectionTitle title="Quick Actions" />
        <div className="grid grid-cols-3 gap-3">
          {[
            { icon: <ClipboardCheck className="w-5 h-5" />, label: 'Mark 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: <Users className="w-5 h-5" />, label: 'Students', color: 'text-orange-500', action: () => navigateTo('students') },
          ].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 Timings */}
      <div>
        <SectionTitle title="Recent Timing Records" />
        <div className="bg-white rounded-2xl card-shadow divide-y divide-gray-50">
          {todayRecords.map((record, i) => (
            <div key={i} className="flex items-center justify-between px-4 py-3">
              <div className="flex items-center gap-3">
                <span className="px-2 py-0.5 bg-orange-100 text-orange-600 text-[10px] font-bold rounded-md">{record.distance}</span>
                <div>
                  <p className="text-sm font-semibold text-gray-900">{record.studentName}</p>
                  <p className="text-[10px] text-gray-400">{record.recordDate}</p>
                </div>
              </div>
              <p className="text-sm font-mono font-bold text-gray-800">{record.timeDisplay}</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
