'use client';

import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { createAnggotaParlemen, updateAnggotaParlemen, deleteAnggotaParlemen } from '@/lib/admin-actions';
import { uploadImage } from '@/lib/upload';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Edit, Trash2, Plus, Users, Upload } from 'lucide-react';
import BulkImportParlemen from '@/components/admin/bulk-import-parlemen';

export default function ParlemenProfilTable({ initialData }: { initialData: any[] }) {
    const [data, setData] = useState(initialData);
    const [isFormOpen, setIsFormOpen] = useState(false);
    const [isBulkOpen, setIsBulkOpen] = useState(false);
    const [selectedItem, setSelectedItem] = useState<any>(null);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [imageFile, setImageFile] = useState<File | null>(null);

    const form = useForm({
        defaultValues: { nama: '', jabatan: '', komisi: '', angkatan: '', linkedinUrl: '', instagramUrl: '' },
    });

    const handleAdd = () => {
        setSelectedItem(null);
        form.reset({ nama: '', jabatan: '', komisi: '', angkatan: '', linkedinUrl: '', instagramUrl: '' });
        setImageFile(null);
        setIsFormOpen(true);
    };

    const handleEdit = (item: any) => {
        setSelectedItem(item);
        form.reset({ 
            nama: item.nama, 
            jabatan: item.jabatan, 
            komisi: item.komisi, 
            angkatan: item.angkatan, 
            linkedinUrl: item.linkedinUrl || '', 
            instagramUrl: item.instagramUrl || '' 
        });
        setImageFile(null);
        setIsFormOpen(true);
    };

    const handleDelete = async (itemId: string) => {
        if (!confirm('Yakin ingin menghapus anggota parlemen ini?')) return;
        const res = await deleteAnggotaParlemen(itemId);
        if (res.success) {
            toast.success(res.message);
            setData((prev) => prev.filter((d) => d.id !== itemId));
        } else {
            toast.error(res.message);
        }
    };

    const onSubmit = async (values: any) => {
        setIsSubmitting(true);
        try {
            let finalImageUrl = selectedItem ? selectedItem.fotoUrl : '';
            if (imageFile) {
                finalImageUrl = await uploadImage(imageFile);
            } else if (!selectedItem && !imageFile) {
                toast.error("Foto wajib diunggah untuk anggota baru.");
                setIsSubmitting(false);
                return;
            }

            const payload = {
                nama: values.nama.trim(),
                jabatan: values.jabatan.trim(),
                komisi: values.komisi.trim(),
                angkatan: values.angkatan.trim(),
                fotoUrl: finalImageUrl,
                linkedinUrl: values.linkedinUrl.trim() || null,
                instagramUrl: values.instagramUrl.trim() || null,
            };

            if (selectedItem) {
                const res = await updateAnggotaParlemen(selectedItem.id, payload);
                if (res.success) {
                    toast.success(res.message);
                    setData((prev) => prev.map((d) => (d.id === selectedItem.id ? { ...d, ...payload } : d)));
                    setIsFormOpen(false);
                    window.location.reload();
                } else {
                    toast.error(res.message);
                }
            } else {
                const res = await createAnggotaParlemen(payload);
                if (res.success) {
                    toast.success(res.message);
                    setIsFormOpen(false);
                    window.location.reload();
                } else {
                    toast.error(res.message);
                }
            }
        } catch (e: any) {
            toast.error('Terjadi kesalahan: ' + e.message);
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <div className="space-y-4">
            <div className="flex justify-between items-center">
                <div className="flex items-center gap-3">
                    <Users className="h-6 w-6 text-primary" />
                    <h2 className="text-xl font-bold">Kelola Anggota Parlemen</h2>
                </div>
                <div className="flex gap-2">
                    <Button variant="outline" onClick={() => setIsBulkOpen(true)} className="gap-2">
                        <Upload className="h-4 w-4" /> Bulk Import
                    </Button>
                    <Button onClick={handleAdd} className="gap-2">
                        <Plus className="h-4 w-4" />
                        Tambah Anggota
                    </Button>
                </div>
            </div>

            <div className="rounded-md border bg-card overflow-x-auto">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Foto</TableHead>
                            <TableHead>Nama</TableHead>
                            <TableHead>Jabatan</TableHead>
                            <TableHead>Komisi</TableHead>
                            <TableHead>Angkatan</TableHead>
                            <TableHead className="text-right">Aksi</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {data.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={7} className="text-center py-10 text-muted-foreground">
                                    Belum ada anggota yang ditambahkan.
                                </TableCell>
                            </TableRow>
                        ) : (
                            data.map((item) => (
                                <TableRow key={item.id}>
                                    <TableCell>
                                        {item.fotoUrl ? (
                                            <img
                                                src={item.fotoUrl}
                                                alt={item.nama}
                                                className="h-10 w-10 object-cover rounded-full border"
                                            />
                                        ) : (
                                            <div className="h-10 w-10 bg-muted rounded-full flex items-center justify-center">-</div>
                                        )}
                                    </TableCell>
                                    <TableCell className="font-medium max-w-[200px] truncate">{item.nama}</TableCell>
                                    <TableCell>{item.jabatan}</TableCell>
                                    <TableCell>{item.komisi}</TableCell>
                                    <TableCell>{item.angkatan}</TableCell>
                                    <TableCell className="text-right space-x-2">
                                        <Button variant="outline" size="icon" onClick={() => handleEdit(item)}>
                                            <Edit className="h-4 w-4 text-primary" />
                                        </Button>
                                        <Button
                                            variant="outline"
                                            size="icon"
                                            className="text-destructive hover:bg-destructive/10"
                                            onClick={() => handleDelete(item.id)}
                                        >
                                            <Trash2 className="h-4 w-4" />
                                        </Button>
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>

            <Dialog open={isFormOpen} onOpenChange={setIsFormOpen}>
                <DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>{selectedItem ? 'Edit Anggota Parlemen' : 'Tambah Anggota Baru'}</DialogTitle>
                    </DialogHeader>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                        <div className="space-y-2">
                            <Label>Nama <span className="text-destructive">*</span></Label>
                            <Input {...form.register('nama', { required: true })} placeholder="Nama Lengkap" />
                        </div>
                        <div className="grid grid-cols-1 gap-4">
                            <div className="space-y-2">
                                <Label>Angkatan <span className="text-destructive">*</span></Label>
                                <Input {...form.register('angkatan', { required: true })} placeholder="Contoh: 2023" />
                            </div>
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label>Jabatan <span className="text-destructive">*</span></Label>
                                <Input {...form.register('jabatan', { required: true })} placeholder="Contoh: Ketua Komisi" />
                            </div>
                            <div className="space-y-2">
                                <Label>Komisi <span className="text-destructive">*</span></Label>
                                <Input {...form.register('komisi', { required: true })} placeholder="Contoh: Komisi I" />
                            </div>
                        </div>
                        <div className="space-y-2">
                            <Label>LinkedIn URL</Label>
                            <Input {...form.register('linkedinUrl')} placeholder="https://linkedin.com/in/..." />
                        </div>
                        <div className="space-y-2">
                            <Label>Instagram URL</Label>
                            <Input {...form.register('instagramUrl')} placeholder="https://instagram.com/..." />
                        </div>
                        <div className="space-y-2">
                            <Label>Foto Profil {!selectedItem && <span className="text-destructive">*</span>}</Label>
                            {selectedItem && selectedItem.fotoUrl && (
                                <div className="mb-2">
                                    <p className="text-xs text-muted-foreground mb-1">Foto saat ini:</p>
                                    <img src={selectedItem.fotoUrl} className="h-20 w-20 object-cover rounded-full border" alt="Preview saat ini" />
                                </div>
                            )}
                            <Input
                                type="file"
                                accept="image/*"
                                onChange={(e) => {
                                    const file = e.target.files?.[0] || null;
                                    setImageFile(file);
                                }}
                            />
                        </div>
                        <div className="flex gap-2 pt-2">
                            <Button type="button" variant="outline" className="flex-1" onClick={() => setIsFormOpen(false)}>
                                Batal
                            </Button>
                            <Button type="submit" className="flex-1" disabled={isSubmitting}>
                                {isSubmitting ? 'Menyimpan...' : selectedItem ? 'Simpan Perubahan' : 'Tambah Anggota'}
                            </Button>
                        </div>
                    </form>
                </DialogContent>
            </Dialog>

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