'use client';

import { useAppStore } from '@/stores/app-store';
import { useEffect, useState } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Progress } from '@/components/ui/progress';
import { Layers, Plus, Filter, CheckCircle2, Clock, Circle } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

const JILID_OPTIONS = ['Jilid 1', 'Jilid 2', 'Jilid 3', 'Jilid 4', 'Jilid 5', 'Jilid 6', 'Ghorib', 'Tajwid Dasar'];
const TOTAL_JILID = JILID_OPTIONS.length;

interface JilidItem {
  id: string;
  santriId: string;
  namaJilid: string;
  halaman: number | null;
  tanggalSelesai: string | null;
  status: string;
  catatanGuru: string | null;
  santri: { nama: string; kelas: string };
}

interface SantriOption {
  id: string;
  nama: string;
  kelas: string;
}

export default function JilidPage() {
  const { token, selectedSantriId, navigate } = useAppStore();
  const { toast } = useToast();
  const [jilidList, setJilidList] = useState<JilidItem[]>([]);
  const [santriOptions, setSantriOptions] = useState<SantriOption[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [filterSantri, setFilterSantri] = useState('');
  const activeFilter = filterSantri || selectedSantriId || '';
  const [form, setForm] = useState({
    santriId: selectedSantriId || '',
    namaJilid: '',
    halaman: '',
    status: 'PROSES',
    tanggalSelesai: '',
    catatanGuru: '',
  });

  const fetchSantri = () => {
    if (!token) return;
    fetch('/api/santri', { headers: { Authorization: `Bearer ${token}` } })
      .then((r) => r.json())
      .then(setSantriOptions);
  };

  const fetchJilid = (filter: string) => {
    if (!token) return;
    const params = new URLSearchParams();
    if (filter) params.set('santriId', filter);
    fetch(`/api/jilid?${params}`, { headers: { Authorization: `Bearer ${token}` } })
      .then((r) => r.json())
      .then((d) => { setJilidList(d); setLoading(false); })
      .catch(() => setLoading(false));
  };

  useEffect(() => { fetchSantri(); }, [token]);
  useEffect(() => { fetchJilid(activeFilter); }, [token, activeFilter]);

  const handleSubmit = async () => {
    if (!token) return;
    const body: Record<string, unknown> = {
      santriId: form.santriId,
      namaJilid: form.namaJilid,
      halaman: form.halaman || null,
      status: form.status,
      catatanGuru: form.catatanGuru || null,
    };
    if (form.tanggalSelesai) body.tanggalSelesai = form.tanggalSelesai;

    const res = await fetch('/api/jilid', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
      body: JSON.stringify(body),
    });
    if (res.ok) {
      toast({ title: 'Berhasil', description: 'Data jilid diperbarui' });
      setDialogOpen(false);
      setForm({ santriId: activeFilter || '', namaJilid: '', halaman: '', status: 'PROSES', tanggalSelesai: '', catatanGuru: '' });
      fetchJilid(activeFilter);
    } else {
      const d = await res.json();
      toast({ title: 'Gagal', description: d.error, variant: 'destructive' });
    }
  };

  const jilidSelesai = jilidList.filter((j) => j.status === 'SELESAI').length;
  const jilidProses = jilidList.filter((j) => j.status === 'PROSES').length;
  const progress = jilidList.length > 0 ? (jilidSelesai / TOTAL_JILID) * 100 : 0;

  // Group by santri for overview
  const santriMap = new Map<string, { nama: string; kelas: string; selesai: number; proses: number; belum: number }>();
  jilidList.forEach((j) => {
    const key = j.santriId;
    if (!santriMap.has(key)) santriMap.set(key, { nama: j.santri.nama, kelas: j.santri.kelas, selesai: 0, proses: 0, belum: 0 });
    const entry = santriMap.get(key)!;
    if (j.status === 'SELESAI') entry.selesai++;
    else if (j.status === 'PROSES') entry.proses++;
    else entry.belum++;
  });

  const statusIcon = (s: string) => {
    if (s === 'SELESAI') return <CheckCircle2 className="w-4 h-4 text-emerald-600" />;
    if (s === 'PROSES') return <Clock className="w-4 h-4 text-amber-600" />;
    return <Circle className="w-4 h-4 text-gray-300" />;
  };

  const statusBg = (s: string) => {
    if (s === 'SELESAI') return 'bg-emerald-50 border-emerald-200';
    if (s === 'PROSES') return 'bg-amber-50 border-amber-200';
    return 'bg-gray-50 border-gray-200';
  };

  const getJilidLabel = (namaJilid: string) => {
    if (namaJilid.startsWith('Jilid ')) return namaJilid.replace('Jilid ', 'J');
    return namaJilid;
  };

  return (
    <div className="space-y-4">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
        <div>
          <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
            <Layers className="w-5 h-5 text-amber-600" /> Batas Jilid
          </h1>
          <p className="text-sm text-gray-500">Tracking progres jilid metode Ummi</p>
        </div>
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogTrigger asChild>
            <Button className="bg-emerald-600 hover:bg-emerald-700 gap-1.5">
              <Plus className="w-4 h-4" /> Update Jilid
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader><DialogTitle>Update Status Jilid</DialogTitle></DialogHeader>
            <div className="space-y-4 py-2">
              <div className="space-y-2">
                <Label>Santri</Label>
                <Select value={form.santriId} onValueChange={(v) => setForm({ ...form, santriId: v })}>
                  <SelectTrigger><SelectValue placeholder="Pilih santri" /></SelectTrigger>
                  <SelectContent>
                    {santriOptions.map((s) => <SelectItem key={s.id} value={s.id}>{s.nama} ({s.kelas})</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Jilid</Label>
                <Select value={form.namaJilid} onValueChange={(v) => setForm({ ...form, namaJilid: v })}>
                  <SelectTrigger><SelectValue placeholder="Pilih jilid" /></SelectTrigger>
                  <SelectContent>
                    {JILID_OPTIONS.map((j) => (
                      <SelectItem key={j} value={j}>{j}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Halaman Jilid</Label>
                <Input
                  type="number"
                  placeholder="0"
                  min={0}
                  value={form.halaman}
                  onChange={(e) => setForm({ ...form, halaman: e.target.value })}
                />
              </div>
              <div className="space-y-2">
                <Label>Status</Label>
                <Select value={form.status} onValueChange={(v) => setForm({ ...form, status: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="BELUM">Belum Mulai</SelectItem>
                    <SelectItem value="PROSES">Sedang Proses</SelectItem>
                    <SelectItem value="SELESAI">Selesai</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              {form.status === 'SELESAI' && (
                <div className="space-y-2">
                  <Label>Tanggal Selesai</Label>
                  <Input type="date" value={form.tanggalSelesai} onChange={(e) => setForm({ ...form, tanggalSelesai: e.target.value })} />
                </div>
              )}
              <div className="space-y-2">
                <Label>Catatan Guru (opsional)</Label>
                <Textarea placeholder="Catatan..." value={form.catatanGuru} onChange={(e) => setForm({ ...form, catatanGuru: e.target.value })} rows={2} />
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setDialogOpen(false)}>Batal</Button>
              <Button className="bg-emerald-600 hover:bg-emerald-700" onClick={handleSubmit}>Simpan</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      {/* Filter */}
      <Card className="border-0 shadow-sm">
        <CardContent className="p-3 flex items-center gap-3">
          <Filter className="w-4 h-4 text-gray-400" />
          <Select value={filterSantri || '__all__'} onValueChange={(v) => setFilterSantri(v === '__all__' ? '' : v)}>
            <SelectTrigger className="w-full sm:w-64"><SelectValue placeholder="Semua santri" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="__all__">Semua Santri</SelectItem>
              {santriOptions.map((s) => <SelectItem key={s.id} value={s.id}>{s.nama}</SelectItem>)}
            </SelectContent>
          </Select>
          {selectedSantriId && (
            <Button variant="ghost" size="sm" onClick={() => { navigate('santri'); }}>Kembali</Button>
          )}
        </CardContent>
      </Card>

      {/* Stats Overview */}
      {filterSantri && (
        <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">{jilidSelesai}</p>
              <p className="text-xs text-gray-500">Jilid Selesai</p>
            </CardContent>
          </Card>
          <Card className="border-0 shadow-sm">
            <CardContent className="p-3 text-center">
              <p className="text-2xl font-bold text-amber-600">{jilidProses}</p>
              <p className="text-xs text-gray-500">Sedang Proses</p>
            </CardContent>
          </Card>
          <Card className="border-0 shadow-sm">
            <CardContent className="p-3 text-center">
              <p className="text-2xl font-bold text-gray-400">{TOTAL_JILID - jilidSelesai - jilidProses}</p>
              <p className="text-xs text-gray-500">Belum Mulai</p>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Progress Bar */}
      {filterSantri && (
        <Card className="border-0 shadow-sm">
          <CardContent className="p-4">
            <div className="flex items-center justify-between mb-2">
              <p className="text-sm font-medium text-gray-700">Progres Jilid ({TOTAL_JILID} Jilid)</p>
              <p className="text-sm font-bold text-emerald-600">{progress.toFixed(0)}%</p>
            </div>
            <Progress value={progress} className="h-3" />
          </CardContent>
        </Card>
      )}

      {/* Santri Overview (no filter) */}
      {!filterSantri && !loading && santriMap.size > 0 && (
        <div className="space-y-3">
          <h2 className="text-sm font-semibold text-gray-700">Ringkasan per Santri</h2>
          <div className="grid sm:grid-cols-2 gap-3">
            {Array.from(santriMap.entries()).map(([id, d]) => (
              <Card key={id} className="border-0 shadow-sm cursor-pointer hover:shadow-md transition-shadow" onClick={() => setFilterSantri(id)}>
                <CardContent className="p-4">
                  <p className="font-semibold text-gray-900">{d.nama}</p>
                  <p className="text-xs text-gray-500 mb-2">Kelas {d.kelas}</p>
                  <div className="flex gap-3 text-xs">
                    <span className="text-emerald-600">{d.selesai} selesai</span>
                    <span className="text-amber-600">{d.proses} proses</span>
                    <span className="text-gray-400">{d.belum} belum</span>
                  </div>
                  <Progress value={(d.selesai / TOTAL_JILID) * 100} className="h-1.5 mt-2" />
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      )}

      {/* Jilid Grid (when filtered) */}
      {filterSantri && !loading && (
        <div className="grid grid-cols-4 sm:grid-cols-4 md:grid-cols-8 gap-2">
          {JILID_OPTIONS.map((jilidName) => {
            const jilid = jilidList.find((j) => j.namaJilid === jilidName);
            const status = jilid?.status || 'BELUM';

            return (
              <div
                key={jilidName}
                className={`aspect-square rounded-xl border-2 flex flex-col items-center justify-center gap-0.5 ${statusBg(status)} transition-colors`}
              >
                {statusIcon(status)}
                <span className="text-[10px] sm:text-xs font-semibold text-center leading-tight px-0.5">{getJilidLabel(jilidName)}</span>
              </div>
            );
          })}
        </div>
      )}

      {/* Jilid Detail List */}
      {loading ? (
        <div className="space-y-2">{Array.from({ length: 3 }).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>
      ) : jilidList.length === 0 ? (
        <Card className="border-0 shadow-sm"><CardContent className="p-8 text-center text-gray-500"><Layers className="w-10 h-10 mx-auto mb-2 text-gray-300" /><p>Belum ada data jilid</p></CardContent></Card>
      ) : filterSantri ? (
        <div className="space-y-2">
          {jilidList
            .filter((j) => j.status !== 'BELUM')
            .map((j) => (
              <Card key={j.id} className="border-0 shadow-sm">
                <CardContent className="p-3 flex items-center justify-between">
                  <div className="flex items-center gap-2 flex-wrap">
                    {statusIcon(j.status)}
                    <span className="font-medium text-gray-900">{j.namaJilid}</span>
                    {j.halaman && (
                      <span className="text-xs text-gray-500">— Halaman {j.halaman}</span>
                    )}
                    <Badge variant="outline" className={j.status === 'SELESAI' ? 'bg-emerald-100 text-emerald-800 border-emerald-200' : 'bg-amber-100 text-amber-800 border-amber-200'}>
                      {j.status}
                    </Badge>
                  </div>
                  <div className="text-right">
                    {j.tanggalSelesai && <p className="text-xs text-gray-500">{new Date(j.tanggalSelesai).toLocaleDateString('id-ID')}</p>}
                    {j.catatanGuru && <p className="text-xs text-gray-400 mt-0.5">{j.catatanGuru}</p>}
                  </div>
                </CardContent>
              </Card>
            ))}
        </div>
      ) : null}
    </div>
  );
}