'use client';

import { useState } from 'react';
import { motion } from 'framer-motion';
import { Plus, Search, Trash2, MoreHorizontal, Pencil } 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 {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select';
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter, DialogClose,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { toast } from 'sonner';

const mockUsers = Array.from({ length: 15 }, (_, i) => ({
  id: `${i + 1}`,
  name: ['Ahmad Fauzi', 'Siti Aisyah', 'Muhammad Ali', 'Fatimah Zahra', 'Umar Farouq'][i % 5],
  email: `user${i + 1}@pesantren.com`,
  role: (['student', 'student', 'student', 'teacher', 'admin'] as const)[i % 5],
  isActive: i % 7 !== 0,
  createdAt: '2024-01-15',
}));

const roleColors: Record<string, string> = {
  student: 'bg-primary/10 text-primary border-primary/20',
  teacher: 'bg-secondary/10 text-secondary border-secondary/20',
  admin: 'bg-destructive/10 text-destructive border-destructive/20',
};

export default function AdminUsersPage() {
  const [search, setSearch] = useState('');
  const [roleFilter, setRoleFilter] = useState('all');
  const [selectedIds, setSelectedIds] = useState<string[]>([]);

  const filtered = mockUsers.filter((u) => {
    const matchSearch = !search || u.name.toLowerCase().includes(search.toLowerCase()) || u.email.toLowerCase().includes(search.toLowerCase());
    const matchRole = roleFilter === 'all' || u.role === roleFilter;
    return matchSearch && matchRole;
  });

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

  return (
    <>
      <title>Kelola Pengguna | 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 pengguna..." value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9 rounded-xl" />
            </div>
            <Select value={roleFilter} onValueChange={setRoleFilter}>
              <SelectTrigger className="w-32 rounded-xl">
                <SelectValue placeholder="Role" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Semua</SelectItem>
                <SelectItem value="student">Siswa</SelectItem>
                <SelectItem value="teacher">Guru</SelectItem>
                <SelectItem value="admin">Admin</SelectItem>
              </SelectContent>
            </Select>
          </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} pengguna dihapus`); setSelectedIds([]); }}>
                <Trash2 className="h-3.5 w-3.5" /> Hapus ({selectedIds.length})
              </Button>
            )}
            <Dialog>
              <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 Pengguna</DialogTitle></DialogHeader>
                <div className="space-y-4 py-4">
                  <div className="space-y-2"><Label>Nama</Label><Input placeholder="Nama lengkap" className="rounded-xl" /></div>
                  <div className="space-y-2"><Label>Email</Label><Input placeholder="email@pesantren.com" className="rounded-xl" /></div>
                  <div className="space-y-2"><Label>Password</Label><Input type="password" placeholder="••••••••" className="rounded-xl" /></div>
                  <div className="space-y-2">
                    <Label>Role</Label>
                    <Select><SelectTrigger className="rounded-xl"><SelectValue placeholder="Pilih role" /></SelectTrigger>
                    <SelectContent><SelectItem value="student">Siswa</SelectItem><SelectItem value="teacher">Guru</SelectItem><SelectItem value="admin">Admin</SelectItem></SelectContent></Select>
                  </div>
                </div>
                <DialogFooter>
                  <DialogClose asChild><Button variant="outline" className="rounded-xl">Batal</Button></DialogClose>
                  <Button className="rounded-xl gradient-primary border-0 text-white" onClick={() => toast.success('Pengguna ditambahkan')}>Simpan</Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </div>

        <div className="rounded-2xl border border-border/50 overflow-hidden">
          <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</TableHead>
                <TableHead className="hidden sm:table-cell">Email</TableHead>
                <TableHead>Role</TableHead>
                <TableHead className="hidden md:table-cell">Status</TableHead>
                <TableHead className="w-10" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map((user) => (
                <TableRow key={user.id}>
                  <TableCell>
                    <input type="checkbox" className="rounded" checked={selectedIds.includes(user.id)} onChange={() => toggleSelect(user.id)} />
                  </TableCell>
                  <TableCell className="font-medium">{user.name}</TableCell>
                  <TableCell className="hidden sm:table-cell text-muted-foreground">{user.email}</TableCell>
                  <TableCell><Badge variant="outline" className={`text-[10px] ${roleColors[user.role]}`}>{user.role}</Badge></TableCell>
                  <TableCell className="hidden md:table-cell">
                    <Badge variant="outline" className={user.isActive ? 'bg-success/10 text-success border-success/20 text-[10px]' : 'bg-muted text-muted-foreground text-[10px]'}>
                      {user.isActive ? 'Aktif' : 'Nonaktif'}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <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><Pencil className="h-3.5 w-3.5 mr-2" /> Edit</DropdownMenuItem>
                        <DropdownMenuItem className="text-destructive"><Trash2 className="h-3.5 w-3.5 mr-2" /> Hapus</DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>

        <p className="text-xs text-muted-foreground text-center">{filtered.length} dari {mockUsers.length} pengguna</p>
      </motion.div>
    </>
  );
}
