'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Plus, Search, Trash2, MoreHorizontal } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table';
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter, DialogClose,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { toast } from 'sonner';
import { adminApi } from '@/services/api/admin';
import { authApi } from '@/services/api/auth';
import { StudentResponse } from '@/types';
import { useRouter } from 'next/navigation';

export default function AdminStudentsPage() {
  const router = useRouter();
  const [search, setSearch] = useState('');
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  
  const [students, setStudents] = useState<StudentResponse[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [isLoading, setIsLoading] = useState(true);

  // Form State
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formData, setFormData] = useState({
    fullName: '',
    nis: '',
    className: '',
    username: '',
    email: '',
    password: '',
  });

  const fetchStudents = async () => {
    setIsLoading(true);
    try {
      const response = await adminApi.getStudents({ page, limit });
      setStudents(response.data);
      setTotal(response.meta.total);
    } catch (error) {
      toast.error('Gagal mengambil data murid');
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchStudents();
  }, [page, limit]);

  const filtered = students.filter((u) => {
    const matchSearch = !search || u.fullName?.toLowerCase().includes(search.toLowerCase()) || u.email?.toLowerCase().includes(search.toLowerCase()) || u.nis?.toLowerCase().includes(search.toLowerCase());
    return matchSearch;
  });

  const toggleSelect = (id: string) => {
    setSelectedIds((prev) => prev.includes(id) ? prev.filter((i) => i !== id) : [...prev, id]);
  };

  const handleAddStudent = async () => {
    if (!formData.fullName || !formData.username || !formData.email || !formData.password || !formData.nis || !formData.className) {
      toast.error('Semua kolom harus diisi');
      return;
    }
    
    setIsSubmitting(true);
    try {
      await authApi.register({
        ...formData,
        role: 'STUDENT',
      });
      toast.success('Murid berhasil ditambahkan');
      setIsDialogOpen(false);
      setFormData({ fullName: '', nis: '', className: '', username: '', email: '', password: '' });
      fetchStudents(); // Refresh list
    } catch (error) {
      toast.error('Gagal menambahkan murid');
      console.error(error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <>
      <title>Kelola Murid | Nadhom Smart</title>
      <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="space-y-4">
        <div className="flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between">
          <div className="flex gap-2 flex-1 w-full sm:w-auto">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input placeholder="Cari murid (nama, email, NIS)..." value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9 rounded-xl" />
            </div>
          </div>
          <div className="flex gap-2">
            {selectedIds.length > 0 && (
              <Button variant="outline" size="sm" className="rounded-xl gap-1 text-destructive" onClick={() => { toast.success(`${selectedIds.length} murid dihapus`); setSelectedIds([]); }}>
                <Trash2 className="h-3.5 w-3.5" /> Hapus ({selectedIds.length})
              </Button>
            )}
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
              <DialogTrigger asChild>
                <Button size="sm" className="rounded-xl gap-1 gradient-primary border-0 text-white">
                  <Plus className="h-3.5 w-3.5" /> Tambah
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader><DialogTitle>Tambah Murid</DialogTitle></DialogHeader>
                <div className="space-y-4 py-4">
                  <div className="space-y-2"><Label>Nama Lengkap</Label><Input placeholder="Nama lengkap" value={formData.fullName} onChange={e => setFormData({...formData, fullName: e.target.value})} className="rounded-xl" /></div>
                  <div className="space-y-2"><Label>NIS</Label><Input placeholder="Nomor Induk Santri" value={formData.nis} onChange={e => setFormData({...formData, nis: e.target.value})} className="rounded-xl" /></div>
                  <div className="space-y-2"><Label>Kelas</Label><Input placeholder="Kelas" value={formData.className} onChange={e => setFormData({...formData, className: e.target.value})} className="rounded-xl" /></div>
                  <div className="space-y-2"><Label>Username</Label><Input placeholder="Username" value={formData.username} onChange={e => setFormData({...formData, username: e.target.value})} className="rounded-xl" /></div>
                  <div className="space-y-2"><Label>Email</Label><Input placeholder="email@pesantren.com" value={formData.email} onChange={e => setFormData({...formData, email: e.target.value})} className="rounded-xl" /></div>
                  <div className="space-y-2"><Label>Password</Label><Input type="password" placeholder="••••••••" value={formData.password} onChange={e => setFormData({...formData, password: e.target.value})} className="rounded-xl" /></div>
                </div>
                <DialogFooter>
                  <DialogClose asChild><Button variant="outline" className="rounded-xl" disabled={isSubmitting}>Batal</Button></DialogClose>
                  <Button className="rounded-xl gradient-primary border-0 text-white" onClick={handleAddStudent} disabled={isSubmitting}>
                    {isSubmitting ? 'Menyimpan...' : 'Simpan'}
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </div>

        {/* Desktop View */}
        <div className="hidden md:block rounded-2xl border border-border/50 overflow-hidden bg-card">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-10">
                  <input type="checkbox" className="rounded" onChange={(e) => setSelectedIds(e.target.checked ? filtered.map((u) => u.id) : [])} checked={selectedIds.length === filtered.length && filtered.length > 0} />
                </TableHead>
                <TableHead>Nama Lengkap</TableHead>
                <TableHead>NIS</TableHead>
                <TableHead>Kelas</TableHead>
                <TableHead>Email</TableHead>
                <TableHead>Role</TableHead>
                <TableHead className="w-10" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-4">Memuat data...</TableCell>
                </TableRow>
              ) : filtered.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-4 text-muted-foreground">Tidak ada data murid</TableCell>
                </TableRow>
              ) : filtered.map((user) => (
                <TableRow key={user.id} className="cursor-pointer hover:bg-muted/50" onClick={() => router.push(`/admin/students/${user.id}`)}>
                  <TableCell onClick={(e) => e.stopPropagation()}>
                    <input type="checkbox" className="rounded" checked={selectedIds.includes(user.id)} onChange={() => toggleSelect(user.id)} />
                  </TableCell>
                  <TableCell className="font-medium">
                    {user.fullName}
                  </TableCell>
                  <TableCell className="text-muted-foreground">{user.nis || '-'}</TableCell>
                  <TableCell className="text-muted-foreground">{user.className || '-'}</TableCell>
                  <TableCell className="text-muted-foreground">{user.email}</TableCell>
                  <TableCell><Badge variant="outline" className="bg-primary/10 text-primary border-primary/20 text-[10px]">{user.role}</Badge></TableCell>
                  <TableCell onClick={(e) => e.stopPropagation()}>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild><Button variant="ghost" size="icon" className="h-8 w-8"><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem className="text-destructive"><Trash2 className="h-3.5 w-3.5 mr-2" /> Hapus</DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>

        {/* Mobile View */}
        <div className="grid grid-cols-1 gap-3 md:hidden">
          {isLoading ? (
            <div className="text-center py-8 text-muted-foreground bg-card rounded-2xl border border-border/50">Memuat data...</div>
          ) : filtered.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground bg-card rounded-2xl border border-border/50">Tidak ada data murid</div>
          ) : filtered.map((user) => (
            <motion.div 
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              key={user.id} 
              className="p-4 rounded-2xl border border-border/50 bg-card flex flex-col gap-3 shadow-sm cursor-pointer hover:bg-muted/50 transition-colors"
              onClick={() => router.push(`/admin/students/${user.id}`)}
            >
              <div className="flex justify-between items-start">
                <div className="flex items-start gap-3">
                  <div className="mt-1" onClick={(e) => e.stopPropagation()}>
                    <input type="checkbox" className="rounded" checked={selectedIds.includes(user.id)} onChange={() => toggleSelect(user.id)} />
                  </div>
                  <div>
                    <h3 className="font-semibold text-sm text-foreground line-clamp-1">{user.fullName}</h3>
                    <p className="text-xs text-muted-foreground line-clamp-1">{user.nis ? `NIS: ${user.nis}` : user.email}</p>
                  </div>
                </div>
                <div onClick={(e) => e.stopPropagation()}>
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild><Button variant="ghost" size="icon" className="h-8 w-8 -mr-2 -mt-1"><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>
                    <DropdownMenuContent align="end" className="rounded-xl">
                      <DropdownMenuItem className="text-destructive rounded-lg"><Trash2 className="h-3.5 w-3.5 mr-2" /> Hapus</DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
              </div>
              <div className="flex items-center justify-between pl-7 border-t border-border/30 pt-3 mt-1">
                <span className="text-xs text-muted-foreground font-medium">{user.className ? `Kelas ${user.className}` : `@${user.username}`}</span>
                <Badge variant="outline" className="bg-primary/10 text-primary border-primary/20 text-[10px]">{user.role}</Badge>
              </div>
            </motion.div>
          ))}
        </div>

        <div className="flex items-center justify-between">
          <p className="text-xs text-muted-foreground">{filtered.length} dari {total} murid</p>
          <div className="flex gap-2">
            <Button 
              variant="outline" 
              size="sm" 
              disabled={page === 1} 
              onClick={() => setPage(p => p - 1)}
              className="h-8"
            >
              Sebelumnya
            </Button>
            <Button 
              variant="outline" 
              size="sm" 
              disabled={filtered.length < limit} 
              onClick={() => setPage(p => p + 1)}
              className="h-8"
            >
              Selanjutnya
            </Button>
          </div>
        </div>
      </motion.div>
    </>
  );
}
