'use client';

import { useAppStore } from '@/stores/app-store';
import { useEffect, useState } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Progress } from '@/components/ui/progress';
import { Users, Search, GraduationCap, BookOpen, Layers, BookMarked } from 'lucide-react';

interface SantriItem {
  id: string;
  nama: string;
  kelas: string;
  kelompokBacaan: string;
  guruId: string;
  guruNama: string;
  totalHafalan: number;
  hafalanKuat: number;
  totalNgaji: number;
  totalJilidSelesai: number;
  totalJilid: number;
}

interface GuruOption {
  id: string;
  nama: string;
}

export default function KepsekSantriPage() {
  const { token } = useAppStore();
  const [santriList, setSantriList] = useState<SantriItem[]>([]);
  const [guruOptions, setGuruOptions] = useState<GuruOption[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [filterGuru, setFilterGuru] = useState('');
  const [filterKelas, setFilterKelas] = useState('');

  useEffect(() => {
    if (!token) return;
    // Fetch guru options
    fetch('/api/kepsek/guru', { headers: { Authorization: `Bearer ${token}` } })
      .then((r) => r.json())
      .then((d) => setGuruOptions(d.map((g: { id: string; nama: string }) => ({ id: g.id, nama: g.nama }))));
  }, [token]);

  useEffect(() => {
    if (!token) return;
    const params = new URLSearchParams();
    if (search) params.set('search', search);
    if (filterKelas) params.set('kelas', filterKelas);
    if (filterGuru) params.set('guruId', filterGuru);
    fetch(`/api/kepsek/santri?${params}`, { headers: { Authorization: `Bearer ${token}` } })
      .then((r) => r.json())
      .then((d) => { setSantriList(d); setLoading(false); })
      .catch(() => setLoading(false));
  }, [token, search, filterKelas, filterGuru]);

  const kelasList = [...new Set(santriList.map((s) => s.kelas))].sort();
  const kelompokColor = (k: string) => {
    const map: Record<string, string> = { Pemula: 'bg-blue-100 text-blue-800', Menengah: 'bg-amber-100 text-amber-800', Lanjutan: 'bg-emerald-100 text-emerald-800' };
    return map[k] || 'bg-gray-100 text-gray-800';
  };

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
          <Users className="w-5 h-5 text-emerald-600" /> Capaian Seluruh Santri
        </h1>
        <p className="text-sm text-gray-500">Lihat progres semua santri dari semua guru</p>
      </div>

      {/* Filters */}
      <Card className="border-0 shadow-sm">
        <CardContent className="p-3 flex flex-col sm:flex-row gap-3">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <Input placeholder="Cari nama santri..." className="pl-9" value={search} onChange={(e) => setSearch(e.target.value)} />
          </div>
          <Select value={filterGuru || '__all__'} onValueChange={(v) => setFilterGuru(v === '__all__' ? '' : v)}>
            <SelectTrigger className="w-full sm:w-48"><SelectValue placeholder="Semua guru" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="__all__">Semua Guru</SelectItem>
              {guruOptions.map((g) => <SelectItem key={g.id} value={g.id}>{g.nama}</SelectItem>)}
            </SelectContent>
          </Select>
          <Select value={filterKelas || '__all__'} onValueChange={(v) => setFilterKelas(v === '__all__' ? '' : v)}>
            <SelectTrigger className="w-full sm:w-32"><SelectValue placeholder="Kelas" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="__all__">Semua Kelas</SelectItem>
              {kelasList.map((k) => <SelectItem key={k} value={k}>{k}</SelectItem>)}
            </SelectContent>
          </Select>
        </CardContent>
      </Card>

      {/* Summary */}
      <div className="grid grid-cols-3 gap-3">
        <Card className="border-0 shadow-sm">
          <CardContent className="p-3 text-center">
            <p className="text-2xl font-bold text-emerald-600">{santriList.length}</p>
            <p className="text-xs text-gray-500">Total Santri</p>
          </CardContent>
        </Card>
        <Card className="border-0 shadow-sm">
          <CardContent className="p-3 text-center">
            <p className="text-2xl font-bold text-teal-600">{santriList.reduce((a, s) => a + s.hafalanKuat, 0)}</p>
            <p className="text-xs text-gray-500">Total Hafalan Kuat</p>
          </CardContent>
        </Card>
        <Card className="border-0 shadow-sm">
          <CardContent className="p-3 text-center">
            <p className="text-2xl font-bold text-amber-600">{santriList.reduce((a, s) => a + s.totalJilidSelesai, 0)}</p>
            <p className="text-xs text-gray-500">Total Jilid Selesai</p>
          </CardContent>
        </Card>
      </div>

      {/* Santri Table/Cards */}
      {loading ? (
        <div className="space-y-2">{Array.from({ length: 5 }).map((_, i) => <Card key={i} className="border-0 shadow-sm"><CardContent className="p-4"><div className="h-4 w-48 bg-gray-200 rounded animate-pulse" /></CardContent></Card>)}</div>
      ) : (
        <Card className="border-0 shadow-sm overflow-hidden">
          {/* Desktop Table */}
          <div className="hidden md:block overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-gray-50 border-b">
                  <th className="text-left p-3 font-semibold text-gray-600">Santri</th>
                  <th className="text-left p-3 font-semibold text-gray-600">Guru</th>
                  <th className="text-center p-3 font-semibold text-gray-600">Hafalan</th>
                  <th className="text-center p-3 font-semibold text-gray-600">Kuat</th>
                  <th className="text-center p-3 font-semibold text-gray-600">Ngaji</th>
                  <th className="text-center p-3 font-semibold text-gray-600">Jilid</th>
                  <th className="p-3 font-semibold text-gray-600">Progres</th>
                </tr>
              </thead>
              <tbody>
                {santriList.map((s) => (
                  <tr key={s.id} className="border-b last:border-0 hover:bg-gray-50">
                    <td className="p-3">
                      <p className="font-medium text-gray-900">{s.nama}</p>
                      <div className="flex items-center gap-1.5 mt-0.5">
                        <span className="text-xs text-gray-500">Kelas {s.kelas}</span>
                        <Badge variant="secondary" className={`text-[10px] ${kelompokColor(s.kelompokBacaan)}`}>{s.kelompokBacaan}</Badge>
                      </div>
                    </td>
                    <td className="p-3">
                      <div className="flex items-center gap-1.5">
                        <GraduationCap className="w-3.5 h-3.5 text-purple-500" />
                        <span className="text-gray-700">{s.guruNama}</span>
                      </div>
                    </td>
                    <td className="p-3 text-center">{s.totalHafalan}</td>
                    <td className="p-3 text-center"><span className="text-emerald-600 font-semibold">{s.hafalanKuat}</span></td>
                    <td className="p-3 text-center">{s.totalNgaji}</td>
                    <td className="p-3 text-center"><span className="font-semibold text-amber-600">{s.totalJilidSelesai}</span><span className="text-gray-400">/8</span></td>
                    <td className="p-3 w-28">
                      <Progress value={(s.totalJilidSelesai / 8) * 100} className="h-2" />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Mobile Cards */}
          <div className="md:hidden divide-y">
            {santriList.map((s) => (
              <div key={s.id} className="p-4">
                <div className="flex items-start justify-between">
                  <div>
                    <p className="font-semibold text-gray-900">{s.nama}</p>
                    <p className="text-xs text-gray-500 mt-0.5">Kelas {s.kelas} — <span className="text-purple-600">{s.guruNama}</span></p>
                    <Badge variant="secondary" className={`mt-1 text-[10px] ${kelompokColor(s.kelompokBacaan)}`}>{s.kelompokBacaan}</Badge>
                  </div>
                  <div className="text-right">
                    <p className="text-lg font-bold text-amber-600">{s.totalJilidSelesai}<span className="text-xs text-gray-400 font-normal">/8 jilid</span></p>
                  </div>
                </div>
                <div className="grid grid-cols-3 gap-2 mt-3">
                  <div className="text-center p-1.5 bg-teal-50 rounded-lg">
                    <p className="text-sm font-bold text-teal-700">{s.totalHafalan}</p>
                    <p className="text-[10px] text-gray-500">Hafalan</p>
                  </div>
                  <div className="text-center p-1.5 bg-emerald-50 rounded-lg">
                    <p className="text-sm font-bold text-emerald-700">{s.hafalanKuat}</p>
                    <p className="text-[10px] text-gray-500">Kuat</p>
                  </div>
                  <div className="text-center p-1.5 bg-sky-50 rounded-lg">
                    <p className="text-sm font-bold text-sky-700">{s.totalNgaji}</p>
                    <p className="text-[10px] text-gray-500">Ngaji</p>
                  </div>
                </div>
                <Progress value={(s.totalJilidSelesai / 8) * 100} className="h-1.5 mt-2" />
              </div>
            ))}
          </div>
        </Card>
      )}
    </div>
  );
}