'use client';

import { useState } from 'react';
import { CalendarDays, Plus, Edit2, Trash2, X, Check, Clock, ImageIcon } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { createAcara, updateAcara, deleteAcara } from '@/lib/admin-actions';
import { uploadImage } from '@/lib/upload';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { id } from 'date-fns/locale';
import Link from 'next/link';

const STATUS_STYLES: Record<string, string> = {
    AKTIF: 'bg-green-50 text-green-700 border-green-200',
    SELESAI: 'bg-blue-50 text-blue-700 border-blue-200',
    DRAFT: 'bg-slate-100 text-slate-500 border-slate-200',
};

export default function AcaraTable({ initialData }: { initialData: any[] }) {
    const [data, setData] = useState(initialData);
    const [isFormOpen, setIsFormOpen] = useState(false);
    const [selectedItem, setSelectedItem] = useState<any>(null);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [imageFile, setImageFile] = useState<File | null>(null);
    const [imagePreview, setImagePreview] = useState<string | null>(null);
    const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);

    const form = useForm({
        defaultValues: { slug: '', nama: '', deskripsi: '', status: 'DRAFT', createdAt: '' },
    });

    const handleAdd = () => {
        setSelectedItem(null);
        form.reset({ slug: '', nama: '', deskripsi: '', status: 'DRAFT', createdAt: format(new Date(), 'yyyy-MM-dd') });
        setImageFile(null); setImagePreview(null);
        setIsFormOpen(true);
    };

    const handleEdit = (item: any) => {
        setSelectedItem(item);
        form.reset({
            slug: item.slug, nama: item.nama, deskripsi: item.deskripsi,
            status: item.status, createdAt: format(new Date(item.createdAt), 'yyyy-MM-dd'),
        });
        setImageFile(null); setImagePreview(item.fotoUrl || null);
        setIsFormOpen(true);
    };

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

    const onSubmit = async (values: any) => {
        setIsSubmitting(true);
        try {
            let finalImageUrl = selectedItem?.fotoUrl ?? null;
            if (imageFile) finalImageUrl = await uploadImage(imageFile);
            const payload = {
                slug: values.slug.trim(), nama: values.nama.trim(), deskripsi: values.deskripsi.trim(),
                status: values.status, fotoUrl: finalImageUrl,
                createdAt: values.createdAt ? new Date(values.createdAt) : new Date(),
            };
            if (selectedItem) {
                const res = await updateAcara(selectedItem.id, payload);
                if (res.success) { toast.success(res.message); setData(prev => prev.map(d => d.id === selectedItem.id ? { ...d, ...payload } : d)); setIsFormOpen(false); }
                else toast.error(res.message);
            } else {
                const res = await createAcara(payload);
                if (res.success) { toast.success(res.message); setIsFormOpen(false); window.location.reload(); }
                else toast.error(res.message);
            }
        } catch (e: any) { toast.error('Gagal', { description: e.message }); }
        finally { setIsSubmitting(false); }
    };

    const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file) return;
        setImageFile(file);
        const reader = new FileReader();
        reader.onload = ev => setImagePreview(ev.target?.result as string);
        reader.readAsDataURL(file);
    };

    const inputCls = "w-full px-3.5 py-2.5 rounded-lg border border-slate-200 text-sm text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-400/10 transition-all bg-white";
    const labelCls = "block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1.5";

    return (
        <div>
            {/* Header */}
            <div className="flex items-start justify-between mb-8">
                <div>
                    <h2 className="text-xl font-bold text-slate-800">Kelola Acara</h2>
                    <p className="text-sm text-slate-400 mt-0.5">{data.length} acara terdaftar</p>
                </div>
                <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 Acara
                </button>
            </div>

            {/* Cards */}
            {data.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-24 bg-white border border-slate-200 rounded-2xl">
                    <CalendarDays className="w-12 h-12 text-slate-200 mb-3" />
                    <p className="text-sm font-semibold text-slate-500">Belum ada acara</p>
                </div>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
                    {data.map(item => (
                        <div key={item.id} className="group relative bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all duration-200">
                            {/* Image */}
                            <div className="aspect-video bg-slate-100 overflow-hidden">
                                {item.fotoUrl ? (
                                    // eslint-disable-next-line @next/next/no-img-element
                                    <img src={item.fotoUrl} alt={item.nama} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" />
                                ) : (
                                    <div className="w-full h-full flex items-center justify-center">
                                        <ImageIcon className="w-10 h-10 text-slate-200" />
                                    </div>
                                )}
                                {/* Status badge on image */}
                                <div className="absolute top-3 left-3">
                                    <span className={`text-[10px] font-bold px-2.5 py-1 rounded-full border ${STATUS_STYLES[item.status] || STATUS_STYLES.DRAFT}`}>
                                        {item.status}
                                    </span>
                                </div>
                            </div>

                            {/* Content */}
                            <div className="p-4 flex flex-col flex-1 h-full">
                                <div>
                                    <p className="text-[10px] font-mono text-slate-400 mb-1">/{item.slug}</p>
                                    <h3 className="font-bold text-slate-800 leading-tight mb-1.5">{item.nama}</h3>
                                    <p className="text-xs text-slate-500 line-clamp-2 leading-relaxed">{item.deskripsi}</p>
                                </div>
                                <div className="flex items-center justify-between mt-auto pt-4">
                                    <div className="flex items-center gap-1.5 text-[10px] font-medium text-slate-400">
                                        <Clock className="w-3 h-3" />
                                        {format(new Date(item.createdAt), 'd MMM yyyy', { locale: id })}
                                    </div>
                                    <Link href={`/admin/acara/${item.slug}`} className="text-[11px] font-bold text-blue-600 hover:text-blue-700 bg-blue-50 hover:bg-blue-100 px-3 py-1.5 rounded-lg transition-colors shadow-sm">
                                        Kelola Tabs
                                    </Link>
                                </div>
                            </div>

                            {/* Delete confirm overlay */}
                            {deleteConfirmId === item.id ? (
                                <div className="absolute inset-0 bg-red-50/96 backdrop-blur-sm flex flex-col items-center justify-center gap-3 p-4">
                                    <p className="text-sm font-bold text-red-700 text-center">Hapus "{item.nama}"?</p>
                                    <div className="flex gap-2">
                                        <button onClick={() => setDeleteConfirmId(null)} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-white border border-slate-200 text-slate-600 text-xs font-semibold hover:bg-slate-50">
                                            <X className="w-3.5 h-3.5" /> Batal
                                        </button>
                                        <button onClick={() => handleDelete(item.id)} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-red-600 text-white text-xs font-semibold hover:bg-red-700">
                                            <Check className="w-3.5 h-3.5" /> Ya, Hapus
                                        </button>
                                    </div>
                                </div>
                            ) : (
                                /* Action buttons */
                                <div className="absolute top-3 right-3 flex gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity">
                                    <button onClick={() => handleEdit(item)} className="p-1.5 rounded-lg bg-white/90 backdrop-blur-sm border border-slate-200 text-slate-500 hover:bg-blue-50 hover:text-blue-600 shadow-sm transition-all">
                                        <Edit2 className="w-3.5 h-3.5" />
                                    </button>
                                    <button onClick={() => setDeleteConfirmId(item.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:text-red-600 shadow-sm transition-all">
                                        <Trash2 className="w-3.5 h-3.5" />
                                    </button>
                                </div>
                            )}
                        </div>
                    ))}
                </div>
            )}

            {/* Modal */}
            {isFormOpen && (
                <div className="fixed inset-0 bg-black/40 backdrop-blur-sm z-50 flex items-center justify-center p-4">
                    <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-hidden flex flex-col">
                        <div className="px-6 py-5 border-b border-slate-100 flex items-center gap-3">
                            <div className="w-9 h-9 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center">
                                <CalendarDays className="w-4.5 h-4.5 text-blue-600" />
                            </div>
                            <div className="flex-1">
                                <h3 className="text-base font-bold text-slate-800">{selectedItem ? 'Edit Acara' : 'Tambah Acara Baru'}</h3>
                                <p className="text-xs text-slate-400">Isi detail informasi acara</p>
                            </div>
                            <button onClick={() => setIsFormOpen(false)} className="p-1.5 rounded-xl hover:bg-slate-100 text-slate-400 transition-colors">
                                <X className="w-4 h-4" />
                            </button>
                        </div>
                        <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col flex-1 overflow-hidden">
                            <div className="px-6 py-5 overflow-y-auto flex-1 space-y-4">
                                <p className={labelCls.replace('mb-1.5', 'mb-3 pb-1.5 border-b border-slate-100 text-slate-400 tracking-widest')}>Informasi Acara</p>
                                <div className="grid grid-cols-2 gap-3">
                                    <div>
                                        <label className={labelCls}>Slug / Singkatan</label>
                                        <input {...form.register('slug')} placeholder="opak-2025" className={inputCls} />
                                    </div>
                                    <div>
                                        <label className={labelCls}>Status</label>
                                        <select {...form.register('status')} className={inputCls}>
                                            <option value="DRAFT">Draft</option>
                                            <option value="AKTIF">Aktif</option>
                                            <option value="SELESAI">Selesai</option>
                                        </select>
                                    </div>
                                </div>
                                <div>
                                    <label className={labelCls}>Nama Acara</label>
                                    <input {...form.register('nama')} placeholder="Orientasi Pengenalan Akademik Kampus" className={inputCls} />
                                </div>
                                <div>
                                    <label className={labelCls}>Deskripsi</label>
                                    <textarea {...form.register('deskripsi')} rows={3} placeholder="Deskripsi singkat acara..." className={`${inputCls} resize-none`} />
                                </div>
                                <div>
                                    <label className={labelCls}>Tanggal</label>
                                    <input type="date" {...form.register('createdAt')} className={inputCls} />
                                </div>
                                <div>
                                    <label className={labelCls}>Foto / Banner</label>
                                    {imagePreview && (
                                        <div className="relative mb-2 rounded-xl overflow-hidden aspect-video border border-slate-200">
                                            {/* eslint-disable-next-line @next/next/no-img-element */}
                                            <img src={imagePreview} alt="preview" className="w-full h-full object-cover" />
                                            <button type="button" onClick={() => { setImagePreview(null); setImageFile(null); }} className="absolute top-2 right-2 p-1 rounded-lg bg-black/50 text-white hover:bg-black/70">
                                                <X className="w-3 h-3" />
                                            </button>
                                        </div>
                                    )}
                                    <label className="flex flex-col items-center gap-2 border-2 border-dashed border-slate-200 rounded-xl p-5 cursor-pointer hover:border-blue-300 hover:bg-blue-50/50 transition-all text-center">
                                        <ImageIcon className="w-6 h-6 text-slate-300" />
                                        <span className="text-xs text-slate-500">{imageFile ? imageFile.name : 'Klik untuk pilih foto banner'}</span>
                                        <input type="file" accept="image/*" className="hidden" onChange={handleImageChange} />
                                    </label>
                                </div>
                            </div>
                            <div className="px-6 py-4 border-t border-slate-100 flex gap-3 justify-end">
                                <button type="button" onClick={() => setIsFormOpen(false)} className="px-4 py-2 rounded-lg border border-slate-200 text-slate-600 text-sm font-medium hover:bg-slate-50 transition-colors">
                                    Batal
                                </button>
                                <button type="submit" disabled={isSubmitting} className="px-5 py-2 rounded-lg bg-[#1e3a5f] text-white text-sm font-semibold hover:bg-[#1e3a5f]/90 transition-colors disabled:opacity-60">
                                    {isSubmitting ? 'Menyimpan...' : 'Simpan'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}
