'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 { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { BookMarked, Plus, Trash2, Filter } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

interface NgajiItem {
  id: string;
  santriId: string;
  juz: number;
  halamanMulai: number;
  halamanAkhir: number;
  tanggal: string;
  kualitas: string;
  catatan: string | null;
  santri: { nama: string; kelas: string };
}

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

export default function NgajiPage() {
  const { token, selectedSantriId, navigate } = useAppStore();
  const { toast } = useToast();
  const [ngajiList, setNgajiList] = useState<NgajiItem[]>([]);
  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 || '',
    juz: '',
    halamanMulai: '',
    halamanAkhir: '',
    kualitas: 'BAIK',
    catatan: '',
  });

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

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

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

  const handleSubmit = async () => {
    if (!token) return;
    const res = await fetch('/api/ngaji', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
      body: JSON.stringify({
        ...form,
        juz: parseInt(form.juz),
        halamanMulai: parseInt(form.halamanMulai),
        halamanAkhir: parseInt(form.halamanAkhir),
      }),
    });
    if (res.ok) {
      toast({ title: 'Berhasil', description: 'Data ngaji ditambahkan' });
      setDialogOpen(false);
      setForm({ santriId: activeFilter || '', juz: '', halamanMulai: '', halamanAkhir: '', kualitas: 'BAIK', catatan: '' });
      fetchNgaji(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/ngaji?id=${id}`, {
      method: 'DELETE',
      headers: { Authorization: `Bearer ${token}` },
    });
    if (res.ok) {
      toast({ title: 'Dihapus', description: 'Data ngaji dihapus' });
      fetchNgaji(activeFilter);
    }
  };

  const kualitasColor = (k: string) => {
    const map: Record<string, string> = {
      'BAIK_SEKALI': 'bg-emerald-100 text-emerald-800 border-emerald-200',
      'BAIK': 'bg-sky-100 text-sky-800 border-sky-200',
      'CUKUP': 'bg-amber-100 text-amber-800 border-amber-200',
      'KURANG': 'bg-red-100 text-red-800 border-red-200',
    };
    return map[k] || 'bg-gray-100 text-gray-800';
  };

  const kualitasLabel = (k: string) => {
    const map: Record<string, string> = {
      'BAIK_SEKALI': 'Baik Sekali',
      BAIK: 'Baik',
      CUKUP: 'Cukup',
      KURANG: 'Kurang',
    };
    return map[k] || k;
  };

  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">
            <BookMarked className="w-5 h-5 text-teal-600" /> Batas Ngaji
          </h1>
          <p className="text-sm text-gray-500">Pencatatan halaman bacaan harian 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 Ngaji
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader><DialogTitle>Catat Batas Ngaji</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>Juz</Label>
                <Select value={form.juz} onValueChange={(v) => setForm({ ...form, juz: v })}>
                  <SelectTrigger><SelectValue placeholder="Pilih juz" /></SelectTrigger>
                  <SelectContent>
                    {Array.from({ length: 30 }, (_, i) => i + 1).map((j) => (
                      <SelectItem key={j} value={String(j)}>Juz {j}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-2">
                  <Label>Halaman Mulai</Label>
                  <Input type="number" placeholder="580" value={form.halamanMulai} onChange={(e) => setForm({ ...form, halamanMulai: e.target.value })} />
                </div>
                <div className="space-y-2">
                  <Label>Halaman Akhir</Label>
                  <Input type="number" placeholder="585" value={form.halamanAkhir} onChange={(e) => setForm({ ...form, halamanAkhir: e.target.value })} />
                </div>
              </div>
              <div className="space-y-2">
                <Label>Kualitas Bacaan</Label>
                <Select value={form.kualitas} onValueChange={(v) => setForm({ ...form, kualitas: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="BAIK_SEKALI">Baik Sekali</SelectItem>
                    <SelectItem value="BAIK">Baik</SelectItem>
                    <SelectItem value="CUKUP">Cukup</SelectItem>
                    <SelectItem value="KURANG">Kurang</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>

      {/* Ngaji 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>
      ) : ngajiList.length === 0 ? (
        <Card className="border-0 shadow-sm"><CardContent className="p-8 text-center text-gray-500"><BookMarked className="w-10 h-10 mx-auto mb-2 text-gray-300" /><p>Belum ada data ngaji</p></CardContent></Card>
      ) : (
        <div className="space-y-2">
          {ngajiList.map((n) => (
            <Card key={n.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">
                      <span className="font-semibold text-gray-900">{n.santri.nama}</span>
                      <Badge variant="outline" className={kualitasColor(n.kualitas)}>
                        {kualitasLabel(n.kualitas)}
                      </Badge>
                    </div>
                    <p className="text-sm text-gray-600 mt-1">
                      Juz <span className="font-medium">{n.juz}</span> — Hlm <span className="font-medium">{n.halamanMulai}</span> s/d <span className="font-medium">{n.halamanAkhir}</span>
                      <span className="text-gray-400 ml-2">({n.halamanAkhir - n.halamanMulai + 1} halaman)</span>
                    </p>
                    <p className="text-xs text-gray-500 mt-0.5">
                      {new Date(n.tanggal).toLocaleDateString('id-ID', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}
                    </p>
                    {n.catatan && <p className="text-xs text-gray-400 mt-1 italic">{n.catatan}</p>}
                  </div>
                  <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 data ngaji?</AlertDialogTitle>
                        <AlertDialogDescription>Data Juz {n.juz} hlm {n.halamanMulai}-{n.halamanAkhir} milik {n.santri.nama} akan dihapus.</AlertDialogDescription>
                      </AlertDialogHeader>
                      <AlertDialogFooter>
                        <AlertDialogCancel>Batal</AlertDialogCancel>
                        <AlertDialogAction onClick={() => handleDelete(n.id)} className="bg-red-600 hover:bg-red-700">Hapus</AlertDialogAction>
                      </AlertDialogFooter>
                    </AlertDialogContent>
                  </AlertDialog>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}