'use client';

import { useAppStore } from '@/stores/app-store';
import { useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Users, GraduationCap, BookOpen, Layers, TrendingUp, Trophy, BarChart3 } from 'lucide-react';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell,
} from 'recharts';

interface KepsekData {
  totalGuru: number;
  totalSantri: number;
  totalHafalanKuat: number;
  totalHafalanBaru: number;
  totalHafalanMurojaah: number;
  totalJilidSelesai: number;
  totalJilidProses: number;
  totalNgaji: number;
  guruStats: { id: string; nama: string; email: string; totalSantri: number; jilidSelesai: number; hafalanKuat: number }[];
  topSantri: { id: string; nama: string; kelas: string; guruNama: string; jilidSelesai: number; hafalanKuat: number; score: number }[];
  kelasStats: { kelas: string; _count: { id: number } }[];
}

const COLORS = ['#059669', '#0d9488', '#d97706', '#dc2626', '#7c3aed', '#2563eb'];

export default function KepsekDashboard() {
  const { token } = useAppStore();
  const [data, setData] = useState<KepsekData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!token) return;
    fetch('/api/kepsek/dashboard', { headers: { Authorization: `Bearer ${token}` } })
      .then((r) => r.json())
      .then((d) => { setData(d); setLoading(false); })
      .catch(() => setLoading(false));
  }, [token]);

  if (loading) return <LoadingSkeleton />;
  if (!data) return <p className="text-gray-500">Gagal memuat data.</p>;

  const stats = [
    { label: 'Total Guru', value: data.totalGuru, icon: <GraduationCap className="w-5 h-5" />, color: 'bg-purple-100 text-purple-700' },
    { label: 'Total Santri', value: data.totalSantri, icon: <Users className="w-5 h-5" />, color: 'bg-emerald-100 text-emerald-700' },
    { label: 'Hafalan Kuat', value: data.totalHafalanKuat, icon: <BookOpen className="w-5 h-5" />, color: 'bg-teal-100 text-teal-700' },
    { label: 'Jilid Selesai', value: data.totalJilidSelesai, icon: <Layers className="w-5 h-5" />, color: 'bg-amber-100 text-amber-700' },
  ];

  const pieData = [
    { name: 'Kuat', value: data.totalHafalanKuat },
    { name: 'Muroja\'ah', value: data.totalHafalanMurojaah },
    { name: 'Baru', value: data.totalHafalanBaru },
  ];

  const guruChartData = data.guruStats.map((g) => ({ name: g.nama.split(' ')[1] || g.nama, santri: g.totalSantri, jilid: g.jilidSelesai }));
  const kelasChartData = data.kelasStats.map((k) => ({ name: k.kelas, santri: k._count.id }));

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-xl font-bold text-gray-900">Dashboard Kepala Sekolah</h1>
        <p className="text-sm text-gray-500">Pantau keseluruhan progres hafalan & bacaan seluruh santri</p>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        {stats.map((s) => (
          <Card key={s.label} className="border-0 shadow-sm">
            <CardContent className="p-4">
              <div className="flex items-center gap-3">
                <div className={`w-10 h-10 rounded-xl flex items-center justify-center ${s.color}`}>{s.icon}</div>
                <div>
                  <p className="text-2xl font-bold text-gray-900">{s.value}</p>
                  <p className="text-xs text-gray-500">{s.label}</p>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Charts */}
      <div className="grid md:grid-cols-3 gap-4">
        <Card className="border-0 shadow-sm">
          <CardHeader className="pb-2 px-4 pt-4"><CardTitle className="text-sm font-semibold">Distribusi Hafalan</CardTitle></CardHeader>
          <CardContent className="px-4 pb-4">
            <ResponsiveContainer width="100%" height={200}>
              <PieChart>
                <Pie data={pieData} cx="50%" cy="50%" innerRadius={50} outerRadius={80} paddingAngle={3} dataKey="value">
                  {pieData.map((_, i) => <Cell key={i} fill={COLORS[i]} />)}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
            <div className="flex justify-center gap-3 text-xs">
              {pieData.map((d, i) => (
                <div key={d.name} className="flex items-center gap-1">
                  <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: COLORS[i] }} />
                  <span className="text-gray-600">{d.name} ({d.value})</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-sm">
          <CardHeader className="pb-2 px-4 pt-4"><CardTitle className="text-sm font-semibold">Santri per Guru</CardTitle></CardHeader>
          <CardContent className="px-4 pb-4">
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={guruChartData}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} />
                <XAxis dataKey="name" tick={{ fontSize: 11 }} />
                <YAxis allowDecimals={false} tick={{ fontSize: 11 }} />
                <Tooltip />
                <Bar dataKey="santri" fill="#059669" radius={[4, 4, 0, 0]} name="Santri" />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-sm">
          <CardHeader className="pb-2 px-4 pt-4"><CardTitle className="text-sm font-semibold">Santri per Kelas</CardTitle></CardHeader>
          <CardContent className="px-4 pb-4">
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={kelasChartData}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} />
                <XAxis dataKey="name" tick={{ fontSize: 11 }} />
                <YAxis allowDecimals={false} tick={{ fontSize: 11 }} />
                <Tooltip />
                <Bar dataKey="santri" fill="#7c3aed" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>

      {/* Top Santri & Guru Performance */}
      <div className="grid md:grid-cols-2 gap-4">
        <Card className="border-0 shadow-sm">
          <CardHeader className="pb-2 px-4 pt-4">
            <CardTitle className="text-sm font-semibold flex items-center gap-2">
              <Trophy className="w-4 h-4 text-amber-500" /> Top Santri
            </CardTitle>
          </CardHeader>
          <CardContent className="px-4 pb-4">
            <div className="space-y-2 max-h-72 overflow-y-auto">
              {data.topSantri.length === 0 && <p className="text-sm text-gray-400 text-center py-4">Belum ada data</p>}
              {data.topSantri.map((s, i) => (
                <div key={s.id} className="flex items-center justify-between py-2 border-b last:border-0">
                  <div className="flex items-center gap-3">
                    <span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold ${i === 0 ? 'bg-amber-100 text-amber-700' : i === 1 ? 'bg-gray-100 text-gray-600' : i === 2 ? 'bg-orange-100 text-orange-700' : 'bg-gray-50 text-gray-400'}`}>
                      {i + 1}
                    </span>
                    <div>
                      <p className="text-sm font-medium text-gray-900">{s.nama}</p>
                      <p className="text-xs text-gray-500">{s.kelas} — {s.guruNama}</p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-bold text-emerald-600">{s.jilidSelesai} jilid</p>
                    <p className="text-xs text-gray-500">{s.hafalanKuat} hafalan kuat</p>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-sm">
          <CardHeader className="pb-2 px-4 pt-4">
            <CardTitle className="text-sm font-semibold flex items-center gap-2">
              <BarChart3 className="w-4 h-4 text-purple-600" /> Performa Guru
            </CardTitle>
          </CardHeader>
          <CardContent className="px-4 pb-4">
            <div className="space-y-2 max-h-72 overflow-y-auto">
              {data.guruStats.map((g) => (
                <div key={g.id} className="p-3 rounded-xl bg-gray-50 border">
                  <div className="flex items-center justify-between mb-2">
                    <div>
                      <p className="text-sm font-semibold text-gray-900">{g.nama}</p>
                      <p className="text-xs text-gray-500">{g.totalSantri} santri</p>
                    </div>
                    <div className="text-right">
                      <p className="text-sm font-bold text-emerald-600">{g.jilidSelesai} jilid</p>
                      <p className="text-xs text-gray-500">{g.hafalanKuat} hafalan</p>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-2">
                    <div className="text-center p-1.5 bg-white rounded-lg">
                      <p className="text-lg font-bold text-emerald-600">{g.totalSantri}</p>
                      <p className="text-[10px] text-gray-500">Santri</p>
                    </div>
                    <div className="text-center p-1.5 bg-white rounded-lg">
                      <p className="text-lg font-bold text-amber-600">{g.jilidSelesai}</p>
                      <p className="text-[10px] text-gray-500">Jilid Selesai</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

function LoadingSkeleton() {
  return (
    <div className="space-y-6">
      <div className="h-6 w-48 bg-gray-200 rounded animate-pulse" />
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {Array.from({ length: 4 }).map((_, i) => (
          <Card key={i} className="border-0 shadow-sm"><CardContent className="p-4"><div className="h-10 w-10 bg-gray-200 rounded-xl animate-pulse" /></CardContent></Card>
        ))}
      </div>
    </div>
  );
}