'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 { Users, Plus, Search, Pencil, Trash2, Eye } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

interface SantriItem {
  id: string;
  nama: string;
  kelas: string;
  kelompokBacaan: string;
  _count: { hafalan: number; ngaji: number; jilid: number };
}

export default function SantriPage() {
  const { token, navigate, selectSantri } = useAppStore();
  const { toast } = useToast();
  const [santriList, setSantriList] = useState<SantriItem[]>([]);
  const [search, setSearch] = useState('');
  const [filterKelas, setFilterKelas] = useState('');
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [form, setForm] = useState({ nama: '', kelas: '', kelompokBacaan: '', passwordOrtu: '' });
  const [editId, setEditId] = useState('');

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

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

  const handleSubmit = async () => {
    if (!token) return;
    const url = editMode ? '/api/santri' : '/api/santri';
    const method = editMode ? 'PUT' : 'POST';
    const body = editMode ? { id: editId, ...form } : form;

    const res = await fetch(url, {
      method,
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
      body: JSON.stringify(body),
    });

    if (res.ok) {
      toast({ title: editMode ? 'Santri diperbarui' : 'Santri ditambahkan', description: 'Berhasil menyimpan data' });
      setDialogOpen(false);
      resetForm();
      fetchSantri();
    } else {
      const d = await res.json();
      toast({ title: 'Gagal', description: d.error, variant: 'destructive' });
    }
  };

  const handleEdit = (s: SantriItem) => {
    setForm({ nama: s.nama, kelas: s.kelas, kelompokBacaan: s.kelompokBacaan, passwordOrtu: '' });
    setEditId(s.id);
    setEditMode(true);
    setDialogOpen(true);
  };

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

  const resetForm = () => {
    setForm({ nama: '', kelas: '', kelompokBacaan: '', passwordOrtu: '' });
    setEditMode(false);
    setEditId('');
  };

  const openDetail = (s: SantriItem) => {
    selectSantri(s.id);
    navigate('hafalan');
  };

  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';
  };

  const kelasList = [...new Set(santriList.map((s) => s.kelas))].sort();

  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">Data Santri</h1>
          <p className="text-sm text-gray-500">Kelola data santri binaan Anda</p>
        </div>
        <Dialog open={dialogOpen} onOpenChange={(o) => { setDialogOpen(o); if (!o) resetForm(); }}>
          <DialogTrigger asChild>
            <Button className="bg-emerald-600 hover:bg-emerald-700 gap-1.5">
              <Plus className="w-4 h-4" /> Tambah Santri
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{editMode ? 'Edit Santri' : 'Tambah Santri Baru'}</DialogTitle>
            </DialogHeader>
            <div className="space-y-4 py-2">
              <div className="space-y-2">
                <Label>Nama Santri</Label>
                <Input placeholder="Nama lengkap" value={form.nama} onChange={(e) => setForm({ ...form, nama: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>Kelas</Label>
                <Input placeholder="Contoh: 1A, 2B" value={form.kelas} onChange={(e) => setForm({ ...form, kelas: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>Kelompok Bacaan</Label>
                <Select value={form.kelompokBacaan} onValueChange={(v) => setForm({ ...form, kelompokBacaan: v })}>
                  <SelectTrigger><SelectValue placeholder="Pilih kelompok" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="Pemula">Pemula</SelectItem>
                    <SelectItem value="Menengah">Menengah</SelectItem>
                    <SelectItem value="Lanjutan">Lanjutan</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Password untuk Orang Tua</Label>
                <Input type="password" placeholder={editMode ? 'Kosongkan jika tidak diubah' : 'Password login ortu'} value={form.passwordOrtu} onChange={(e) => setForm({ ...form, passwordOrtu: e.target.value })} />
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => { setDialogOpen(false); resetForm(); }}>Batal</Button>
              <Button className="bg-emerald-600 hover:bg-emerald-700" onClick={handleSubmit}>{editMode ? 'Simpan' : 'Tambah'}</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      {/* Search & Filter */}
      <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={filterKelas} onValueChange={(v) => setFilterKelas(v === '__all__' ? '' : v)}>
            <SelectTrigger className="w-full sm:w-36"><SelectValue placeholder="Semua kelas" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="__all__">Semua Kelas</SelectItem>
              {kelasList.map((k) => <SelectItem key={k} value={k}>{k}</SelectItem>)}
            </SelectContent>
          </Select>
        </CardContent>
      </Card>

      {/* Santri Grid */}
      {loading ? (
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3">
          {Array.from({ length: 6 }).map((_, i) => (
            <Card key={i} className="border-0 shadow-sm"><CardContent className="p-4"><div className="h-5 w-32 bg-gray-200 rounded animate-pulse" /><div className="h-4 w-20 bg-gray-200 rounded animate-pulse mt-3" /></CardContent></Card>
          ))}
        </div>
      ) : santriList.length === 0 ? (
        <Card className="border-0 shadow-sm"><CardContent className="p-8 text-center text-gray-500"><Users className="w-10 h-10 mx-auto mb-2 text-gray-300" /><p>Belum ada data santri</p></CardContent></Card>
      ) : (
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3">
          {santriList.map((s) => (
            <Card key={s.id} className="border-0 shadow-sm hover:shadow-md transition-shadow">
              <CardContent className="p-4">
                <div className="flex items-start justify-between">
                  <div className="flex-1 min-w-0">
                    <p className="font-semibold text-gray-900 truncate">{s.nama}</p>
                    <p className="text-xs text-gray-500 mt-0.5">Kelas {s.kelas}</p>
                    <Badge variant="secondary" className={`mt-2 text-[10px] ${kelompokColor(s.kelompokBacaan)}`}>
                      {s.kelompokBacaan}
                    </Badge>
                  </div>
                </div>
                <div className="flex gap-4 mt-3 text-xs text-gray-500">
                  <span>{s._count.hafalan} hafalan</span>
                  <span>{s._count.ngaji} ngaji</span>
                  <span>{s._count.jilid} juz</span>
                </div>
                <div className="flex gap-1.5 mt-3 pt-3 border-t">
                  <Button variant="outline" size="sm" className="flex-1 text-xs h-8 gap-1" onClick={() => openDetail(s)}>
                    <Eye className="w-3 h-3" /> Detail
                  </Button>
                  <Button variant="outline" size="icon" className="h-8 w-8" onClick={() => handleEdit(s)}>
                    <Pencil className="w-3 h-3" />
                  </Button>
                  <AlertDialog>
                    <AlertDialogTrigger asChild>
                      <Button variant="outline" size="icon" className="h-8 w-8 text-red-500 hover:text-red-700">
                        <Trash2 className="w-3 h-3" />
                      </Button>
                    </AlertDialogTrigger>
                    <AlertDialogContent>
                      <AlertDialogHeader>
                        <AlertDialogTitle>Hapus Santri?</AlertDialogTitle>
                        <AlertDialogDescription>
                          Semua data hafalan, ngaji, dan jilid <strong>{s.nama}</strong> juga akan ikut terhapus. Tindakan ini tidak bisa dibatalkan.
                        </AlertDialogDescription>
                      </AlertDialogHeader>
                      <AlertDialogFooter>
                        <AlertDialogCancel>Batal</AlertDialogCancel>
                        <AlertDialogAction onClick={() => handleDelete(s.id)} className="bg-red-600 hover:bg-red-700">Hapus</AlertDialogAction>
                      </AlertDialogFooter>
                    </AlertDialogContent>
                  </AlertDialog>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}