'use client';

import { useState } from 'react';
import { Users, Plus, Edit2, Trash2, X, Check } from 'lucide-react';
import { deletePengurus } from '@/lib/admin-actions';
import { toast } from 'sonner';
import PengurusForm from '@/components/admin/pengurus-form';
import BulkImportPengurus from '@/components/admin/bulk-import-pengurus';
import { Upload } from 'lucide-react';

export default function PengurusTable({
    initialData,
    bidangLembagaList = [],
}: {
    initialData: any[];
    bidangLembagaList?: any[];
}) {
    const [data, setData] = useState(initialData);
    const [isFormOpen, setIsFormOpen] = useState(false);
    const [isBulkOpen, setIsBulkOpen] = useState(false);
    const [selectedItem, setSelectedItem] = useState<any>(null);
    const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);

    const handleEdit = (item: any) => { setSelectedItem(item); setIsFormOpen(true); };
    const handleAdd = () => { setSelectedItem(null); setIsFormOpen(true); };

    const handleDelete = async (id: string) => {
        const res = await deletePengurus(id);
        if (res.success) {
            toast.success(res.message);
            setData(prev => prev.filter(item => item.id !== id));
            setDeleteConfirmId(null);
        } else {
            toast.error(res.message);
        }
    };

    // Group by divisi
    const grouped = data.reduce((acc: Record<string, any[]>, p) => {
        if (!acc[p.divisi]) acc[p.divisi] = [];
        acc[p.divisi].push(p);
        return acc;
    }, {});

    return (
        <div>
            {/* Header */}
            <div className="flex items-start justify-between mb-8">
                <div>
                    <h2 className="text-xl font-bold text-slate-800">Data Pengurus</h2>
                    <p className="text-sm text-slate-400 mt-0.5">{data.length} pengurus terdaftar dalam {Object.keys(grouped).length} divisi</p>
                </div>
                <div className="flex gap-2">
                    <button
                        onClick={() => setIsBulkOpen(true)}
                        className="flex items-center gap-2 bg-slate-100 text-slate-700 border border-slate-300 rounded-lg px-4 py-2 text-sm font-semibold hover:bg-slate-200 transition-colors shadow-sm"
                    >
                        <Upload className="w-4 h-4" /> Bulk Import
                    </button>
                    <button
                        onClick={handleAdd}
                        className="flex items-center gap-2 bg-[#1e3a5f] text-white rounded-lg px-4 py-2 text-sm font-semibold hover:bg-[#1e3a5f]/90 transition-colors shadow-sm"
                    >
                        <Plus className="w-4 h-4" /> Tambah Pengurus
                    </button>
                </div>
            </div>

            {data.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-24 bg-white border border-slate-200 rounded-2xl">
                    <div className="w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center mb-4">
                        <Users className="w-8 h-8 text-slate-300" />
                    </div>
                    <p className="text-sm font-semibold text-slate-500">Belum ada pengurus</p>
                    <p className="text-xs text-slate-400 mt-1">Klik "Tambah Pengurus" untuk memulai</p>
                </div>
            ) : (
                <div className="space-y-10">
                    {Object.entries(grouped).map(([divisi, members]) => (
                        <div key={divisi}>
                            {/* Divisi label */}
                            <div className="flex items-center gap-3 mb-4">
                                <div className="h-px flex-1 bg-slate-200" />
                                <span className="text-xs font-bold uppercase tracking-widest text-slate-500 px-3 py-1 bg-slate-100 rounded-full border border-slate-200">
                                    {divisi}
                                </span>
                                <div className="h-px flex-1 bg-slate-200" />
                            </div>

                            {/* Staff cards */}
                            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
                                {members.map(member => (
                                    <div key={member.id} className="group relative bg-white border border-slate-200 rounded-xl overflow-hidden shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all duration-200">
                                        {/* Portrait photo */}
                                        <div className="aspect-[3/4] bg-slate-100 overflow-hidden">
                                            {member.fotoUrl ? (
                                                // eslint-disable-next-line @next/next/no-img-element
                                                <img
                                                    src={member.fotoUrl}
                                                    alt={member.nama}
                                                    className="w-full h-full object-cover object-top group-hover:scale-105 transition-transform duration-500"
                                                />
                                            ) : (
                                                <div className="w-full h-full flex items-center justify-center">
                                                    <Users className="w-10 h-10 text-slate-300" />
                                                </div>
                                            )}
                                        </div>

                                        {/* Info */}
                                        <div className="p-3">
                                            <p className="text-xs font-bold text-slate-800 leading-tight truncate">{member.nama}</p>
                                            <p className="text-[10px] text-slate-400 mt-0.5 truncate">{member.jabatan}</p>
                                            {member.angkatan && (
                                                <span className="inline-block mt-1.5 text-[9px] font-semibold bg-blue-50 text-blue-600 border border-blue-200 px-1.5 py-0.5 rounded-full">
                                                    {member.angkatan}
                                                </span>
                                            )}
                                        </div>

                                        {/* Hover action overlay */}
                                        {deleteConfirmId === member.id ? (
                                            <div className="absolute inset-0 bg-red-50/95 backdrop-blur-sm flex flex-col items-center justify-center gap-2 p-3">
                                                <p className="text-xs font-bold text-red-700 text-center">Hapus {member.nama}?</p>
                                                <div className="flex gap-2">
                                                    <button onClick={() => setDeleteConfirmId(null)} className="p-1.5 rounded-lg bg-white border border-slate-200 text-slate-500 hover:bg-slate-50">
                                                        <X className="w-3.5 h-3.5" />
                                                    </button>
                                                    <button onClick={() => handleDelete(member.id)} className="p-1.5 rounded-lg bg-red-600 border border-red-700 text-white hover:bg-red-700">
                                                        <Check className="w-3.5 h-3.5" />
                                                    </button>
                                                </div>
                                            </div>
                                        ) : (
                                            <div className="absolute top-2 right-2 flex flex-col gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                                <button
                                                    onClick={() => handleEdit(member)}
                                                    className="p-1.5 rounded-lg bg-white/90 backdrop-blur-sm border border-slate-200 text-slate-500 hover:bg-blue-50 hover:border-blue-300 hover:text-blue-600 shadow-sm transition-all"
                                                >
                                                    <Edit2 className="w-3 h-3" />
                                                </button>
                                                <button
                                                    onClick={() => setDeleteConfirmId(member.id)}
                                                    className="p-1.5 rounded-lg bg-white/90 backdrop-blur-sm border border-slate-200 text-slate-500 hover:bg-red-50 hover:border-red-300 hover:text-red-600 shadow-sm transition-all"
                                                >
                                                    <Trash2 className="w-3 h-3" />
                                                </button>
                                            </div>
                                        )}
                                    </div>
                                ))}
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {isFormOpen && (
                <PengurusForm
                    isOpen={isFormOpen}
                    setIsOpen={setIsFormOpen}
                    initialData={selectedItem}
                    bidangLembagaList={bidangLembagaList}
                />
            )}

            {isBulkOpen && (
                <BulkImportPengurus isOpen={isBulkOpen} setIsOpen={setIsBulkOpen} />
            )}
        </div>
    );
}
