'use client';

import { useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import {
    upsertUKKInfo,
    createUKKProker,
    updateUKKProker,
    deleteUKKProker,
    createUKKAnggota,
    updateUKKAnggota,
    deleteUKKAnggota,
} from '@/lib/admin-actions';
import { uploadImage } from '@/lib/upload';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import BulkImportUKKAnggota from '@/components/admin/bulk-import-ukk';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} from '@/components/ui/dialog';
import {
    Pencil,
    Trash2,
    Plus,
    Save,
    Info,
    Briefcase,
    Users,
    X,
    Upload
} from 'lucide-react';

// ===== TYPES =====
type UKKProker = {
    id: string;
    judul: string;
    deskripsi: string | null;
    ukkId: string;
    createdAt: string;
};

type UKKAnggota = {
    id: string;
    nama: string;
    jabatan: string;
    fotoUrl: string | null;
    ukkId: string;
};

type UKKData = {
    id: string;
    slug: string;
    nama: string;
    deskripsi: string;
    visi: string | null;
    misi: string | null;
    logoUrl: string | null;
    proker: UKKProker[];
    anggota: UKKAnggota[];
};

// ===== MAIN COMPONENT =====
export default function UKKClientPage({ initialUKK }: { initialUKK: UKKData }) {
    const router = useRouter();
    const [, startTransition] = useTransition();
    const [ukk, setUKK] = useState<UKKData>(initialUKK);

    const refresh = () => startTransition(() => router.refresh());

    return (
        <div className="space-y-6">
            <InfoSection ukk={ukk} setUKK={setUKK} refresh={refresh} />
            <ProkerSection ukk={ukk} setUKK={setUKK} refresh={refresh} />
            <AnggotaSection ukk={ukk} setUKK={setUKK} refresh={refresh} />
        </div>
    );
}

// ===========================
// SECTION A: Edit Info UKK
// ===========================
function InfoSection({
    ukk,
    setUKK,
    refresh,
}: {
    ukk: UKKData;
    setUKK: React.Dispatch<React.SetStateAction<UKKData>>;
    refresh: () => void;
}) {
    const [nama, setNama] = useState(ukk.nama);
    const [deskripsi, setDeskripsi] = useState(ukk.deskripsi);
    const [visi, setVisi] = useState(ukk.visi ?? '');
    const [misi, setMisi] = useState(ukk.misi ?? '');
    const [logoUrl, setLogoUrl] = useState(ukk.logoUrl ?? '');
    const [logoFile, setLogoFile] = useState<File | null>(null);
    const [isSaving, setIsSaving] = useState(false);

    const handleSave = async () => {
        if (!nama.trim() || !deskripsi.trim()) {
            toast.error('Nama dan Deskripsi wajib diisi');
            return;
        }
        setIsSaving(true);
        try {
            let finalLogoUrl = logoUrl;
            if (logoFile) {
                finalLogoUrl = await uploadImage(logoFile);
            }
            const result = await upsertUKKInfo(ukk.id, {
                nama: nama.trim(),
                deskripsi: deskripsi.trim(),
                visi: visi.trim() || undefined,
                misi: misi.trim() || undefined,
                logoUrl: finalLogoUrl.trim() || undefined,
            });
            if (result.success) {
                toast.success(result.message);
                setUKK((prev) => ({ ...prev, nama, deskripsi, visi, misi, logoUrl: finalLogoUrl }));
                setLogoFile(null);
                refresh();
            } else {
                toast.error(result.message);
            }
        } catch (e: any) {
            toast.error('Error: ' + e.message);
        } finally {
            setIsSaving(false);
        }
    };

    return (
        <Card>
            <CardHeader>
                <div className="flex items-center gap-2">
                    <div className="p-2 bg-primary/10 rounded-lg">
                        <Info className="h-4 w-4 text-primary" />
                    </div>
                    <div>
                        <CardTitle className="text-base">Informasi UKK</CardTitle>
                        <CardDescription>Edit nama, deskripsi, visi, misi, dan logo UKK.</CardDescription>
                    </div>
                </div>
            </CardHeader>
            <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                        <Label>Nama UKK</Label>
                        <Input value={nama} onChange={(e) => setNama(e.target.value)} placeholder="Nama UKK..." />
                    </div>
                    <div className="space-y-2">
                        <Label>Unggah Logo</Label>
                        <div className="flex gap-2 items-center">
                            {logoUrl && (
                                <img src={logoUrl} className="w-10 h-10 object-contain rounded border bg-white" alt="logo" />
                            )}
                            <Input
                                type="file"
                                accept="image/*"
                                onChange={(e) => setLogoFile(e.target.files?.[0] || null)}
                            />
                        </div>
                    </div>
                </div>

                <div className="space-y-2">
                    <Label>Deskripsi</Label>
                    <Textarea
                        value={deskripsi}
                        onChange={(e) => setDeskripsi(e.target.value)}
                        placeholder="Deskripsi singkat UKK..."
                        rows={3}
                    />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                        <Label>Visi <span className="text-muted-foreground text-xs">(opsional)</span></Label>
                        <Textarea
                            value={visi}
                            onChange={(e) => setVisi(e.target.value)}
                            placeholder="Visi UKK..."
                            rows={3}
                        />
                    </div>
                    <div className="space-y-2">
                        <Label>Misi <span className="text-muted-foreground text-xs">(opsional)</span></Label>
                        <Textarea
                            value={misi}
                            onChange={(e) => setMisi(e.target.value)}
                            placeholder="Misi UKK..."
                            rows={3}
                        />
                    </div>
                </div>

                <div className="flex justify-end pt-2">
                    <Button onClick={handleSave} disabled={isSaving}>
                        <Save className="h-4 w-4 mr-2" />
                        {isSaving ? 'Menyimpan...' : 'Simpan Info'}
                    </Button>
                </div>
            </CardContent>
        </Card>
    );
}

// ===========================
// SECTION B: Program Kerja
// ===========================
function ProkerSection({
    ukk,
    setUKK,
    refresh,
}: {
    ukk: UKKData;
    setUKK: React.Dispatch<React.SetStateAction<UKKData>>;
    refresh: () => void;
}) {
    const [showAddForm, setShowAddForm] = useState(false);
    const [addJudul, setAddJudul] = useState('');
    const [addDeskripsi, setAddDeskripsi] = useState('');
    const [isAdding, setIsAdding] = useState(false);

    // Edit dialog
    const [editItem, setEditItem] = useState<UKKProker | null>(null);
    const [editJudul, setEditJudul] = useState('');
    const [editDeskripsi, setEditDeskripsi] = useState('');
    const [isEditing, setIsEditing] = useState(false);
    const [deletingId, setDeletingId] = useState<string | null>(null);

    const handleAdd = async () => {
        if (!addJudul.trim()) { toast.error('Judul wajib diisi'); return; }
        setIsAdding(true);
        try {
            const result = await createUKKProker({
                judul: addJudul.trim(),
                deskripsi: addDeskripsi.trim() || undefined,
                ukkId: ukk.id,
            });
            if (result.success) {
                toast.success(result.message);
                setAddJudul(''); setAddDeskripsi(''); setShowAddForm(false);
                refresh();
            } else { toast.error(result.message); }
        } catch (e: any) { toast.error(e.message); } finally { setIsAdding(false); }
    };

    const openEdit = (item: UKKProker) => {
        setEditItem(item);
        setEditJudul(item.judul);
        setEditDeskripsi(item.deskripsi ?? '');
    };

    const handleEdit = async () => {
        if (!editItem || !editJudul.trim()) { toast.error('Judul wajib diisi'); return; }
        setIsEditing(true);
        try {
            const result = await updateUKKProker(editItem.id, {
                judul: editJudul.trim(),
                deskripsi: editDeskripsi.trim() || undefined,
            });
            if (result.success) {
                toast.success(result.message);
                setUKK((prev) => ({
                    ...prev,
                    proker: prev.proker.map((p) =>
                        p.id === editItem.id
                            ? { ...p, judul: editJudul.trim(), deskripsi: editDeskripsi.trim() || null }
                            : p
                    ),
                }));
                setEditItem(null);
            } else { toast.error(result.message); }
        } catch (e: any) { toast.error(e.message); } finally { setIsEditing(false); }
    };

    const handleDelete = async (id: string, judul: string) => {
        if (!confirm(`Hapus proker "${judul}"?`)) return;
        setDeletingId(id);
        try {
            const result = await deleteUKKProker(id);
            if (result.success) {
                toast.success(result.message);
                setUKK((prev) => ({ ...prev, proker: prev.proker.filter((p) => p.id !== id) }));
            } else { toast.error(result.message); }
        } catch (e: any) { toast.error(e.message); } finally { setDeletingId(null); }
    };

    return (
        <Card>
            <CardHeader>
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                        <div className="p-2 bg-primary/10 rounded-lg">
                            <Briefcase className="h-4 w-4 text-primary" />
                        </div>
                        <div>
                            <CardTitle className="text-base">Program Kerja</CardTitle>
                            <CardDescription>Daftar program kerja UKK {ukk.nama}.</CardDescription>
                        </div>
                    </div>
                    <Button size="sm" onClick={() => setShowAddForm(!showAddForm)} variant={showAddForm ? 'outline' : 'default'}>
                        {showAddForm ? <X className="h-4 w-4 mr-1" /> : <Plus className="h-4 w-4 mr-1" />}
                        {showAddForm ? 'Batal' : 'Tambah'}
                    </Button>
                </div>
            </CardHeader>
            <CardContent className="space-y-4">
                {/* Add form inline */}
                {showAddForm && (
                    <div className="border border-dashed border-primary/40 rounded-lg p-4 space-y-3 bg-primary/5">
                        <div className="space-y-1">
                            <Label className="text-xs">Judul Program Kerja</Label>
                            <Input
                                value={addJudul}
                                onChange={(e) => setAddJudul(e.target.value)}
                                placeholder="Nama proker..."
                            />
                        </div>
                        <div className="space-y-1">
                            <Label className="text-xs">Deskripsi <span className="text-muted-foreground">(opsional)</span></Label>
                            <Textarea
                                value={addDeskripsi}
                                onChange={(e) => setAddDeskripsi(e.target.value)}
                                placeholder="Deskripsi singkat..."
                                rows={2}
                            />
                        </div>
                        <div className="flex justify-end">
                            <Button size="sm" onClick={handleAdd} disabled={isAdding}>
                                {isAdding ? 'Menambahkan...' : 'Tambah Proker'}
                            </Button>
                        </div>
                    </div>
                )}

                {/* List */}
                {ukk.proker.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground text-sm">
                        Belum ada program kerja. Klik &quot;Tambah&quot; untuk menambahkan.
                    </div>
                ) : (
                    <div className="divide-y divide-border rounded-lg border border-border overflow-hidden">
                        {ukk.proker.map((p, i) => (
                            <div key={p.id} className="flex items-start gap-3 px-4 py-3">
                                <span className="text-xs font-mono text-muted-foreground mt-1 w-5 shrink-0">{i + 1}.</span>
                                <div className="flex-1 min-w-0">
                                    <p className="font-medium text-sm text-foreground">{p.judul}</p>
                                    {p.deskripsi && (
                                        <p className="text-xs text-muted-foreground mt-0.5 line-clamp-2">{p.deskripsi}</p>
                                    )}
                                </div>
                                <div className="flex gap-1 shrink-0">
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-8 w-8 text-muted-foreground hover:text-foreground"
                                        onClick={() => openEdit(p)}
                                    >
                                        <Pencil className="h-3.5 w-3.5" />
                                    </Button>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-8 w-8 text-destructive hover:bg-destructive/10"
                                        onClick={() => handleDelete(p.id, p.judul)}
                                        disabled={deletingId === p.id}
                                    >
                                        <Trash2 className="h-3.5 w-3.5" />
                                    </Button>
                                </div>
                            </div>
                        ))}
                    </div>
                )}

                {ukk.proker.length > 0 && (
                    <p className="text-xs text-muted-foreground text-right">
                        Total: <span className="font-semibold">{ukk.proker.length}</span> program kerja
                    </p>
                )}
            </CardContent>

            {/* Edit Dialog */}
            <Dialog open={!!editItem} onOpenChange={(o) => { if (!o) setEditItem(null); }}>
                <DialogContent className="max-w-md">
                    <DialogHeader>
                        <DialogTitle>Edit Program Kerja</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4 py-2">
                        <div className="space-y-2">
                            <Label>Judul</Label>
                            <Input value={editJudul} onChange={(e) => setEditJudul(e.target.value)} />
                        </div>
                        <div className="space-y-2">
                            <Label>Deskripsi</Label>
                            <Textarea
                                value={editDeskripsi}
                                onChange={(e) => setEditDeskripsi(e.target.value)}
                                rows={3}
                            />
                        </div>
                    </div>
                    <DialogFooter>
                        <Button variant="ghost" onClick={() => setEditItem(null)}>Batal</Button>
                        <Button onClick={handleEdit} disabled={isEditing}>
                            {isEditing ? 'Menyimpan...' : 'Simpan'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </Card>
    );
}

// ===========================
// SECTION C: Anggota
// ===========================
function AnggotaSection({
    ukk,
    setUKK,
    refresh,
}: {
    ukk: UKKData;
    setUKK: React.Dispatch<React.SetStateAction<UKKData>>;
    refresh: () => void;
}) {
    const [showAddForm, setShowAddForm] = useState(false);
    const [addNama, setAddNama] = useState('');
    const [addJabatan, setAddJabatan] = useState('');
    const [addFotoUrl, setAddFotoUrl] = useState('');
    const [addFotoFile, setAddFotoFile] = useState<File | null>(null);
    const [isAdding, setIsAdding] = useState(false);
    const [isBulkOpen, setIsBulkOpen] = useState(false);

    const [editItem, setEditItem] = useState<UKKAnggota | null>(null);
    const [editNama, setEditNama] = useState('');
    const [editJabatan, setEditJabatan] = useState('');
    const [editFotoUrl, setEditFotoUrl] = useState('');
    const [editFotoFile, setEditFotoFile] = useState<File | null>(null);
    const [isEditing, setIsEditing] = useState(false);
    const [deletingId, setDeletingId] = useState<string | null>(null);

    const handleAdd = async () => {
        if (!addNama.trim() || !addJabatan.trim()) {
            toast.error('Nama dan Jabatan wajib diisi');
            return;
        }
        setIsAdding(true);
        try {
            let finalFotoUrl = addFotoUrl.trim() || undefined;
            if (addFotoFile) {
                finalFotoUrl = await uploadImage(addFotoFile);
            }
            const result = await createUKKAnggota({
                nama: addNama.trim(),
                jabatan: addJabatan.trim(),
                fotoUrl: finalFotoUrl,
                ukkId: ukk.id,
            });
            if (result.success) {
                toast.success(result.message);
                setAddNama(''); setAddJabatan(''); setAddFotoUrl(''); setAddFotoFile(null);
                setShowAddForm(false);
                refresh();
            } else { toast.error(result.message); }
        } catch (e: any) { toast.error(e.message); } finally { setIsAdding(false); }
    };

    const openEdit = (item: UKKAnggota) => {
        setEditItem(item);
        setEditNama(item.nama);
        setEditJabatan(item.jabatan);
        setEditFotoUrl(item.fotoUrl ?? '');
        setEditFotoFile(null);
    };

    const handleEdit = async () => {
        if (!editItem || !editNama.trim() || !editJabatan.trim()) {
            toast.error('Nama dan Jabatan wajib diisi');
            return;
        }
        setIsEditing(true);
        try {
            let finalFotoUrl = editFotoUrl.trim() || undefined;
            if (editFotoFile) {
                finalFotoUrl = await uploadImage(editFotoFile);
            }
            const result = await updateUKKAnggota(editItem.id, {
                nama: editNama.trim(),
                jabatan: editJabatan.trim(),
                fotoUrl: finalFotoUrl,
            });
            if (result.success) {
                toast.success(result.message);
                setUKK((prev) => ({
                    ...prev,
                    anggota: prev.anggota.map((a) =>
                        a.id === editItem.id
                            ? { ...a, nama: editNama.trim(), jabatan: editJabatan.trim(), fotoUrl: finalFotoUrl || null }
                            : a
                    ),
                }));
                setEditFotoFile(null);
                setEditItem(null);
            } else { toast.error(result.message); }
        } catch (e: any) { toast.error(e.message); } finally { setIsEditing(false); }
    };

    const handleDelete = async (id: string, nama: string) => {
        if (!confirm(`Hapus anggota "${nama}"?`)) return;
        setDeletingId(id);
        try {
            const result = await deleteUKKAnggota(id);
            if (result.success) {
                toast.success(result.message);
                setUKK((prev) => ({ ...prev, anggota: prev.anggota.filter((a) => a.id !== id) }));
            } else { toast.error(result.message); }
        } catch (e: any) { toast.error(e.message); } finally { setDeletingId(null); }
    };

    return (
        <Card>
            <CardHeader>
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                        <div className="p-2 bg-primary/10 rounded-lg">
                            <Users className="h-4 w-4 text-primary" />
                        </div>
                        <div>
                            <CardTitle className="text-base">Anggota UKK</CardTitle>
                            <CardDescription>Daftar anggota aktif UKK {ukk.nama}.</CardDescription>
                        </div>
                    </div>
                    <div className="flex gap-2">
                        <Button size="sm" variant="outline" onClick={() => setIsBulkOpen(true)}>
                            <Upload className="h-4 w-4 mr-1" />
                            Bulk Import
                        </Button>
                        <Button size="sm" onClick={() => setShowAddForm(!showAddForm)} variant={showAddForm ? 'outline' : 'default'}>
                            {showAddForm ? <X className="h-4 w-4 mr-1" /> : <Plus className="h-4 w-4 mr-1" />}
                            {showAddForm ? 'Batal' : 'Tambah'}
                        </Button>
                    </div>
                </div>
            </CardHeader>
            <CardContent className="space-y-4">
                {/* Add form */}
                {showAddForm && (
                    <div className="border border-dashed border-primary/40 rounded-lg p-4 space-y-3 bg-primary/5">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                            <div className="space-y-1">
                                <Label className="text-xs">Nama Lengkap</Label>
                                <Input value={addNama} onChange={(e) => setAddNama(e.target.value)} placeholder="Nama anggota..." />
                            </div>
                            <div className="space-y-1">
                                <Label className="text-xs">Jabatan</Label>
                                <Input value={addJabatan} onChange={(e) => setAddJabatan(e.target.value)} placeholder="Ketua / Sekretaris / dll." />
                            </div>
                        </div>
                        <div className="space-y-1">
                            <Label className="text-xs">Foto Anggota <span className="text-muted-foreground">(opsional)</span></Label>
                            <Input
                                type="file"
                                accept="image/*"
                                onChange={(e) => setAddFotoFile(e.target.files?.[0] || null)}
                            />
                        </div>
                        <div className="flex justify-end">
                            <Button size="sm" onClick={handleAdd} disabled={isAdding}>
                                {isAdding ? 'Menambahkan...' : 'Tambah Anggota'}
                            </Button>
                        </div>
                    </div>
                )}

                {/* Grid list */}
                {ukk.anggota.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground text-sm">
                        Belum ada anggota. Klik &quot;Tambah&quot; untuk menambahkan.
                    </div>
                ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                        {ukk.anggota.map((a) => (
                            <div
                                key={a.id}
                                className="border border-border rounded-lg p-3 flex items-center gap-3 group hover:border-primary/30 transition-colors"
                            >
                                {/* Avatar */}
                                <div className="shrink-0">
                                    {a.fotoUrl ? (
                                        <img
                                            src={a.fotoUrl}
                                            alt={a.nama}
                                            className="w-10 h-10 rounded-full object-cover border border-border"
                                        />
                                    ) : (
                                        <div className="w-10 h-10 rounded-full bg-muted flex items-center justify-center text-muted-foreground font-bold text-sm">
                                            {a.nama.charAt(0).toUpperCase()}
                                        </div>
                                    )}
                                </div>

                                {/* Info */}
                                <div className="flex-1 min-w-0">
                                    <p className="font-medium text-sm text-foreground truncate">{a.nama}</p>
                                    <Badge variant="secondary" className="text-xs mt-0.5">{a.jabatan}</Badge>
                                </div>

                                {/* Actions */}
                                <div className="flex flex-col gap-1 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-7 w-7 text-muted-foreground hover:text-foreground"
                                        onClick={() => openEdit(a)}
                                    >
                                        <Pencil className="h-3 w-3" />
                                    </Button>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-7 w-7 text-destructive hover:bg-destructive/10"
                                        onClick={() => handleDelete(a.id, a.nama)}
                                        disabled={deletingId === a.id}
                                    >
                                        <Trash2 className="h-3 w-3" />
                                    </Button>
                                </div>
                            </div>
                        ))}
                    </div>
                )}

                {ukk.anggota.length > 0 && (
                    <p className="text-xs text-muted-foreground text-right">
                        Total: <span className="font-semibold">{ukk.anggota.length}</span> anggota
                    </p>
                )}
            </CardContent>

            {/* Edit Dialog */}
            <Dialog open={!!editItem} onOpenChange={(o) => { if (!o) setEditItem(null); }}>
                <DialogContent className="max-w-md">
                    <DialogHeader>
                        <DialogTitle>Edit Anggota</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4 py-2">
                        <div className="space-y-2">
                            <Label>Nama Lengkap</Label>
                            <Input value={editNama} onChange={(e) => setEditNama(e.target.value)} />
                        </div>
                        <div className="space-y-2">
                            <Label>Jabatan</Label>
                            <Input value={editJabatan} onChange={(e) => setEditJabatan(e.target.value)} />
                        </div>
                        <div className="space-y-2">
                            <Label>Foto Anggota <span className="text-muted-foreground text-xs">(opsional)</span></Label>
                            {editFotoUrl && (
                                <div className="mb-2">
                                    <p className="text-xs text-muted-foreground mb-1">Foto saat ini:</p>
                                    <img src={editFotoUrl} className="w-10 h-10 rounded-full object-cover border" alt="preview" />
                                </div>
                            )}
                            <Input
                                type="file"
                                accept="image/*"
                                onChange={(e) => setEditFotoFile(e.target.files?.[0] || null)}
                            />
                        </div>
                    </div>
                    <DialogFooter>
                        <Button variant="ghost" onClick={() => setEditItem(null)}>Batal</Button>
                        <Button onClick={handleEdit} disabled={isEditing}>
                            {isEditing ? 'Menyimpan...' : 'Simpan'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {isBulkOpen && (
                <BulkImportUKKAnggota isOpen={isBulkOpen} setIsOpen={setIsBulkOpen} ukkId={ukk.id} />
            )}
        </Card>
    );
}
