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

interface GuruItem {
  id: string;
  nama: string;
  email: string;
  totalSantri: number;
  hafalanKuat: number;
  hafalanMurojaah: number;
  hafalanBaru: number;
  totalHafalan: number;
  totalJilidSelesai: number;
  totalJilidProses: number;
  totalNgaji: number;
}

export default function KepsekGuruPage() {
  const { token } = useAppStore();
  const { toast } = useToast();
  const [guruList, setGuruList] = useState<GuruItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [editId, setEditId] = useState('');
  const [form, setForm] = useState({ nama: '', email: '', password: '' });

  const fetchGuru = () => {
    if (!token) return;
    fetch('/api/kepsek/guru', { headers: { Authorization: `Bearer ${token}` } })
      .then((r) => r.json())
      .then((d) => { setGuruList(d); setLoading(false); })
      .catch(() => setLoading(false));
  };

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

  const handleSubmit = async () => {
    if (!token) return;
    const url = editMode ? '/api/kepsek/guru' : '/api/kepsek/guru';
    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 ? 'Guru diperbarui' : 'Guru ditambahkan', description: 'Berhasil menyimpan data' });
      setDialogOpen(false);
      setForm({ nama: '', email: '', password: '' });
      setEditMode(false);
      fetchGuru();
    } else {
      const d = await res.json();
      toast({ title: 'Gagal', description: d.error, variant: 'destructive' });
    }
  };

  const handleEdit = (g: GuruItem) => {
    setForm({ nama: g.nama, email: g.email, password: '' });
    setEditId(g.id);
    setEditMode(true);
    setDialogOpen(true);
  };

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

  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">
            <GraduationCap className="w-5 h-5 text-purple-600" /> Manajemen Guru
          </h1>
          <p className="text-sm text-gray-500">Kelola akun guru dan pantau performa mereka</p>
        </div>
        <Dialog open={dialogOpen} onOpenChange={(o) => { setDialogOpen(o); if (!o) { setForm({ nama: '', email: '', password: '' }); setEditMode(false); } }}>
          <DialogTrigger asChild>
            <Button className="bg-emerald-600 hover:bg-emerald-700 gap-1.5">
              <Plus className="w-4 h-4" /> Tambah Guru
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{editMode ? 'Edit Guru' : 'Tambah Guru Baru'}</DialogTitle>
            </DialogHeader>
            <div className="space-y-4 py-2">
              <div className="space-y-2">
                <Label>Nama Lengkap</Label>
                <Input placeholder="Ustadz/Ustadzah ..." value={form.nama} onChange={(e) => setForm({ ...form, nama: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>Email</Label>
                <Input type="email" placeholder="email@guru.com" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>Password {editMode && <span className="text-gray-400 font-normal">(kosongkan jika tidak diubah)</span>}</Label>
                <Input type="password" placeholder={editMode ? 'Kosongkan jika tidak diubah' : 'Password login'} value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} />
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => { setDialogOpen(false); setEditMode(false); }}>Batal</Button>
              <Button className="bg-emerald-600 hover:bg-emerald-700" onClick={handleSubmit}>{editMode ? 'Simpan' : 'Tambah'}</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      {loading ? (
        <div className="grid sm:grid-cols-2 gap-3">
          {Array.from({ length: 4 }).map((_, i) => <Card key={i} className="border-0 shadow-sm"><CardContent className="p-4"><div className="h-5 w-40 bg-gray-200 rounded animate-pulse" /><div className="h-4 w-24 bg-gray-200 rounded animate-pulse mt-3" /></CardContent></Card>)}
        </div>
      ) : guruList.length === 0 ? (
        <Card className="border-0 shadow-sm"><CardContent className="p-8 text-center text-gray-500"><GraduationCap className="w-10 h-10 mx-auto mb-2 text-gray-300" /><p>Belum ada data guru</p></CardContent></Card>
      ) : (
        <div className="space-y-3">
          {guruList.map((g) => (
            <Card key={g.id} className="border-0 shadow-sm hover:shadow-md transition-shadow">
              <CardContent className="p-4 md:p-5">
                <div className="flex flex-col sm:flex-row sm:items-start gap-4">
                  {/* Avatar */}
                  <div className="w-12 h-12 rounded-xl bg-purple-100 flex items-center justify-center shrink-0">
                    <GraduationCap className="w-6 h-6 text-purple-600" />
                  </div>

                  {/* Info */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <p className="font-semibold text-gray-900">{g.nama}</p>
                      <Badge variant="secondary" className="bg-purple-100 text-purple-800 text-[10px]">{g.email}</Badge>
                    </div>

                    {/* Stats Grid */}
                    <div className="grid grid-cols-4 gap-2 mt-3">
                      <div className="text-center p-2 bg-emerald-50 rounded-lg">
                        <p className="text-lg font-bold text-emerald-700">{g.totalSantri}</p>
                        <p className="text-[10px] text-gray-500">Santri</p>
                      </div>
                      <div className="text-center p-2 bg-teal-50 rounded-lg">
                        <p className="text-lg font-bold text-teal-700">{g.totalHafalan}</p>
                        <p className="text-[10px] text-gray-500">Hafalan</p>
                      </div>
                      <div className="text-center p-2 bg-amber-50 rounded-lg">
                        <p className="text-lg font-bold text-amber-700">{g.totalJilidSelesai}</p>
                        <p className="text-[10px] text-gray-500">Jilid</p>
                      </div>
                      <div className="text-center p-2 bg-sky-50 rounded-lg">
                        <p className="text-lg font-bold text-sky-700">{g.totalNgaji}</p>
                        <p className="text-[10px] text-gray-500">Ngaji</p>
                      </div>
                    </div>

                    {/* Detail badges */}
                    <div className="flex gap-2 mt-2 text-xs flex-wrap">
                      <span className="text-emerald-600 font-medium">{g.hafalanKuat} kuat</span>
                      <span className="text-amber-600 font-medium">{g.hafalanMurojaah} muroja&apos;ah</span>
                      <span className="text-sky-600 font-medium">{g.hafalanBaru} baru</span>
                      <span className="text-gray-400">|</span>
                      <span className="text-gray-500">{g.totalJilidProses} jilid proses</span>
                    </div>
                  </div>

                  {/* Actions */}
                  <div className="flex gap-1.5 sm:flex-col">
                    <Button variant="outline" size="icon" className="h-8 w-8" onClick={() => handleEdit(g)}>
                      <Pencil className="w-3.5 h-3.5" />
                    </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.5 h-3.5" />
                        </Button>
                      </AlertDialogTrigger>
                      <AlertDialogContent>
                        <AlertDialogHeader>
                          <AlertDialogTitle>Hapus Guru?</AlertDialogTitle>
                          <AlertDialogDescription>
                            Semua data <strong>{g.nama}</strong> beserta {g.totalSantri} santri dan seluruh data hafalan/ngaji/jilid mereka akan <strong>dihapus permanen</strong>.
                          </AlertDialogDescription>
                        </AlertDialogHeader>
                        <AlertDialogFooter>
                          <AlertDialogCancel>Batal</AlertDialogCancel>
                          <AlertDialogAction onClick={() => handleDelete(g.id)} className="bg-red-600 hover:bg-red-700">Hapus</AlertDialogAction>
                        </AlertDialogFooter>
                      </AlertDialogContent>
                    </AlertDialog>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}