'use client';

import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { createLaporanKeuangan, updateLaporanKeuangan, deleteLaporanKeuangan } from '@/lib/admin-actions';
import { Edit2, Trash2, Plus, FileText, Check, X } from 'lucide-react';
import { format } from 'date-fns';
import { id } from 'date-fns/locale';

export default function LaporanKeuanganTable({ initialData }: { initialData: any[] }) {
    const [data, setData] = useState(initialData);
    const [isFormOpen, setIsFormOpen] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [selectedItem, setSelectedItem] = useState<any>(null);

    const form = useForm({
        defaultValues: { judul: '', periode: '', narasi: '', fileUrl: '', createdAt: '' },
    });

    const openForm = (item?: any) => {
        if (item) {
            setSelectedItem(item);
            form.reset({
                judul: item.judul,
                periode: item.periode,
                narasi: item.narasi || '',
                fileUrl: item.fileUrl || '',
                createdAt: format(new Date(item.createdAt), 'yyyy-MM-dd'),
            });
        } else {
            setSelectedItem(null);
            form.reset({ judul: '', periode: '', narasi: '', fileUrl: '', createdAt: format(new Date(), 'yyyy-MM-dd') });
        }
        setIsFormOpen(true);
    };

    const closeForm = () => {
        setIsFormOpen(false);
        setSelectedItem(null);
        form.reset();
    };

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

    const onSubmit = async (values: any) => {
        setIsSubmitting(true);
        try {
            const payload = {
                judul: values.judul,
                periode: values.periode,
                narasi: values.narasi,
                fileUrl: values.fileUrl,
                createdAt: values.createdAt ? new Date(values.createdAt) : new Date(),
            };

            if (selectedItem) {
                const res = await updateLaporanKeuangan(selectedItem.id, payload);
                if (res.success) {
                    toast.success(res.message);
                    setData((prev) => prev.map((item) => (item.id === selectedItem.id ? { ...item, ...payload } : item)));
                    closeForm();
                } else toast.error(res.message);
            } else {
                const res = await createLaporanKeuangan(payload);
                if (res.success) {
                    toast.success(res.message);
                    setData([{ id: Date.now().toString(), ...payload }, ...data]);
                    closeForm();
                } else toast.error(res.message);
            }
        } catch (e: any) {
            toast.error('Gagal memproses data', { description: e.message });
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <h2 className="text-xl font-bold">Laporan Keuangan</h2>
                <button
                    onClick={() => openForm()}
                    className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-blue-700 transition-colors"
                >
                    <Plus className="w-4 h-4" /> Tambah Laporan
                </button>
            </div>

            {data.length === 0 ? (
                <div className="bg-white border border-slate-200 rounded-xl p-12 text-center text-slate-500">
                    Belum ada laporan keuangan.
                </div>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {data.map((item) => (
                        <div key={item.id} className="bg-white border border-slate-200 rounded-xl overflow-hidden flex flex-col">
                            <div className="p-5 flex-1">
                                <div className="flex justify-between items-start mb-3">
                                    <span className="bg-slate-100 text-slate-600 text-xs font-semibold px-2 py-1 rounded-md">{item.periode}</span>
                                    <span className="text-xs text-slate-400">{format(new Date(item.createdAt), 'dd MMM yyyy', { locale: id as any })}</span>
                                </div>
                                <h3 className="font-bold text-slate-800 text-lg mb-2">{item.judul}</h3>
                                {item.fileUrl && (
                                    <a href={item.fileUrl} target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 text-sm text-blue-600 hover:underline mb-4">
                                        <FileText className="w-4 h-4" /> Lihat PDF
                                    </a>
                                )}
                            </div>
                            <div className="bg-slate-50 border-t border-slate-100 p-3 flex gap-2 justify-end">
                                <button
                                    onClick={() => openForm(item)}
                                    className="p-2 text-slate-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                                >
                                    <Edit2 className="w-4 h-4" />
                                </button>
                                <button
                                    onClick={() => handleDelete(item.id)}
                                    className="p-2 text-slate-500 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                                >
                                    <Trash2 className="w-4 h-4" />
                                </button>
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {isFormOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm overflow-y-auto">
                    <div className="bg-white w-full max-w-xl rounded-2xl shadow-xl my-8">
                        <div className="flex items-center justify-between p-6 border-b border-slate-100">
                            <h3 className="text-xl font-bold text-slate-800">
                                {selectedItem ? 'Edit Laporan Keuangan' : 'Tambah Laporan Keuangan'}
                            </h3>
                            <button onClick={closeForm} className="text-slate-400 hover:text-slate-600 p-2 rounded-full hover:bg-slate-100 transition-colors">
                                <X className="w-5 h-5" />
                            </button>
                        </div>
                        <form onSubmit={form.handleSubmit(onSubmit)} className="p-6 space-y-6">
                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <label className="text-sm font-semibold text-slate-700">Judul Laporan</label>
                                    <input
                                        {...form.register('judul', { required: true })}
                                        className="w-full px-4 py-2 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500 outline-none"
                                        placeholder="Contoh: Laporan Q1"
                                    />
                                </div>
                                <div className="space-y-2">
                                    <label className="text-sm font-semibold text-slate-700">Periode</label>
                                    <input
                                        {...form.register('periode', { required: true })}
                                        className="w-full px-4 py-2 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500 outline-none"
                                        placeholder="Contoh: Januari - Maret 2024"
                                    />
                                </div>
                            </div>
                            <div className="space-y-2">
                                <label className="text-sm font-semibold text-slate-700">Narasi (Opsional)</label>
                                <textarea
                                    {...form.register('narasi')}
                                    className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500 outline-none min-h-[100px]"
                                    placeholder="Penjelasan ringkas terkait laporan keuangan ini..."
                                />
                            </div>
                            <div className="space-y-2">
                                <label className="text-sm font-semibold text-slate-700">Link File PDF</label>
                                <input
                                    {...form.register('fileUrl', { required: true })}
                                    className="w-full px-4 py-2 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500 outline-none"
                                    placeholder="Contoh: https://drive.google.com/..."
                                />
                            </div>
                            <div className="space-y-2">
                                <label className="text-sm font-semibold text-slate-700">Tanggal Posting</label>
                                <input
                                    type="date"
                                    {...form.register('createdAt', { required: true })}
                                    className="w-full px-4 py-2 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500 outline-none"
                                />
                            </div>

                            <div className="pt-4 flex gap-3">
                                <button type="button" onClick={closeForm} className="flex-1 px-4 py-2.5 border border-slate-200 text-slate-600 rounded-xl font-medium hover:bg-slate-50 transition-colors">
                                    Batal
                                </button>
                                <button type="submit" disabled={isSubmitting} className="flex-1 px-4 py-2.5 bg-blue-600 text-white rounded-xl font-medium hover:bg-blue-700 transition-colors disabled:opacity-70 flex items-center justify-center gap-2">
                                    {isSubmitting ? 'Menyimpan...' : (
                                        <>
                                            <Check className="w-4 h-4" /> Simpan Laporan
                                        </>
                                    )}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}
