'use client';

import { useAppStore } from '@/stores/app-store';
import { useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } 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 { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { ScrollArea } from '@/components/ui/scroll-area';
import { BookOpen, Plus, Trash2, Filter } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

interface HafalanItem {
  id: string;
  santriId: string;
  surah: string;
  ayatMulai: number;
  ayatAkhir: number;
  status: string;
  tanggal: string;
  catatan: string | null;
  santri: { nama: string; kelas: string };
}

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

export default function HafalanPage() {
  const { token, selectedSantriId, navigate } = useAppStore();
  const { toast } = useToast();
  const [hafalanList, setHafalanList] = useState<HafalanItem[]>([]);
  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 || '',
    surah: '',
    ayatMulai: '',
    ayatAkhir: '',
    status: 'BARU',
    catatan: '',
  });

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

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

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

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

  const handleSubmit = async () => {
    if (!token) return;
    const res = await fetch('/api/hafalan', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
      body: JSON.stringify({
        ...form,
        ayatMulai: parseInt(form.ayatMulai),
        ayatAkhir: parseInt(form.ayatAkhir),
      }),
    });
    if (res.ok) {
      toast({ title: 'Berhasil', description: 'Data hafalan ditambahkan' });
      setDialogOpen(false);
      setForm({ santriId: activeFilter || '', surah: '', ayatMulai: '', ayatAkhir: '', status: 'BARU', catatan: '' });
      fetchHafalan(activeFilter);
    } else {
      const d = await res.json();
      toast({ title: 'Gagal', description: d.error, variant: 'destructive' });
    }
  };

  const handleDelete = async (id: string) => {
    if (!token) return;
    const res = await fetch(`/api/hafalan?id=${id}`, {
      method: 'DELETE',
      headers: { Authorization: `Bearer ${token}` },
    });
    if (res.ok) {
      toast({ title: 'Dihapus', description: 'Data hafalan dihapus' });
      fetchHafalan(activeFilter);
    }
  };

  const statusColor = (s: string) => {
    const map: Record<string, string> = {
      KUAT: 'bg-emerald-100 text-emerald-800 border-emerald-200',
      "MUROJA'AH": 'bg-amber-100 text-amber-800 border-amber-200',
      BARU: 'bg-sky-100 text-sky-800 border-sky-200',
    };
    return map[s] || 'bg-gray-100 text-gray-800';
  };

  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">
            <BookOpen className="w-5 h-5 text-emerald-600" /> Monitoring Hafalan
          </h1>
          <p className="text-sm text-gray-500">Catat dan pantau progres hafalan santri</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" /> Tambah Hafalan
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader><DialogTitle>Tambah Hafalan Baru</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>Surah</Label>
                <Input placeholder="Contoh: An-Nas" value={form.surah} onChange={(e) => setForm({ ...form, surah: e.target.value })} />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-2">
                  <Label>Ayat Mulai</Label>
                  <Input type="number" placeholder="1" value={form.ayatMulai} onChange={(e) => setForm({ ...form, ayatMulai: e.target.value })} />
                </div>
                <div className="space-y-2">
                  <Label>Ayat Akhir</Label>
                  <Input type="number" placeholder="6" value={form.ayatAkhir} onChange={(e) => setForm({ ...form, ayatAkhir: e.target.value })} />
                </div>
              </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="BARU">Baru</SelectItem>
                    <SelectItem value="MUROJA'AH">Muroja&apos;ah</SelectItem>
                    <SelectItem value="KUAT">Kuat</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Catatan (opsional)</Label>
                <Input placeholder="Catatan tambahan..." value={form.catatan} onChange={(e) => setForm({ ...form, catatan: e.target.value })} />
              </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>

      {/* Hafalan List */}
      {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>
      ) : hafalanList.length === 0 ? (
        <Card className="border-0 shadow-sm"><CardContent className="p-8 text-center text-gray-500"><BookOpen className="w-10 h-10 mx-auto mb-2 text-gray-300" /><p>Belum ada data hafalan</p></CardContent></Card>
      ) : (
        <div className="space-y-2">
          {hafalanList.map((h) => (
            <Card key={h.id} className="border-0 shadow-sm hover:shadow-md transition-shadow">
              <CardContent className="p-4">
                <div className="flex items-start justify-between gap-3">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <p className="font-semibold text-gray-900">{h.surah}</p>
                      <span className="text-sm text-gray-500">ayat {h.ayatMulai}–{h.ayatAkhir}</span>
                    </div>
                    <p className="text-xs text-gray-500 mt-0.5">
                      {h.santri.nama} — Kelas {h.santri.kelas} — {new Date(h.tanggal).toLocaleDateString('id-ID')}
                    </p>
                    {h.catatan && <p className="text-xs text-gray-400 mt-1 italic">{h.catatan}</p>}
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge variant="outline" className={statusColor(h.status)}>
                      {h.status}
                    </Badge>
                    <AlertDialog>
                      <AlertDialogTrigger asChild>
                        <Button variant="ghost" size="icon" className="h-7 w-7 text-gray-400 hover:text-red-600">
                          <Trash2 className="w-3.5 h-3.5" />
                        </Button>
                      </AlertDialogTrigger>
                      <AlertDialogContent>
                        <AlertDialogHeader>
                          <AlertDialogTitle>Hapus hafalan ini?</AlertDialogTitle>
                          <AlertDialogDescription>Data {h.surah} ayat {h.ayatMulai}-{h.ayatAkhir} milik {h.santri.nama} akan dihapus.</AlertDialogDescription>
                        </AlertDialogHeader>
                        <AlertDialogFooter>
                          <AlertDialogCancel>Batal</AlertDialogCancel>
                          <AlertDialogAction onClick={() => handleDelete(h.id)} className="bg-red-600 hover:bg-red-700">Hapus</AlertDialogAction>
                        </AlertDialogFooter>
                      </AlertDialogContent>
                    </AlertDialog>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}