'use client';

import { useState, useRef } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { createBerita, updateBerita, deleteBerita } from '@/lib/admin-actions';
import { uploadImage } from '@/lib/upload';
import { Edit2, Trash2, Plus, Newspaper, X, ImageIcon, Check, Clock } from 'lucide-react';
import { format } from 'date-fns';
import { id } from 'date-fns/locale';

export default function BeritaTable({ 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: { judul: '', narasi: '', imageUrl: '', createdAt: '' } });

    const handleAdd = () => {
        setSelectedItem(null);
        form.reset({ judul: '', narasi: '', imageUrl: '', createdAt: format(new Date(), 'yyyy-MM-dd') });
        setImageFile(null); setImagePreview(null);
        setIsFormOpen(true);
    };

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

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

    const onSubmit = async (values: any) => {
        setIsSubmitting(true);
        try {
            let finalImageUrl = selectedItem ? selectedItem.imageUrl : null;
            if (imageFile) finalImageUrl = await uploadImage(imageFile);
            const payload = { judul: values.judul.trim(), narasi: values.narasi.trim(), imageUrl: finalImageUrl, createdAt: values.createdAt ? new Date(values.createdAt) : new Date() };
            if (selectedItem) {
                const res = await updateBerita(selectedItem.id, payload);
                if (res.success) { toast.success(res.message); setData(prev => prev.map(d => d.id === selectedItem.id ? { ...d, ...payload } : d).sort((a,b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())); setIsFormOpen(false); }
                else toast.error(res.message);
            } else {
                const res = await createBerita(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); }
    };

    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 Berita HMF</h2>
                    <p className="text-sm text-slate-400 mt-0.5">{data.length} berita tersimpan</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 Berita
                </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">
                    <Newspaper className="w-12 h-12 text-slate-200 mb-3" />
                    <p className="text-sm font-semibold text-slate-500">Belum ada berita</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 flex flex-col">
                            {/* Thumbnail */}
                            <div className="aspect-video bg-slate-100 overflow-hidden">
                                {item.imageUrl ? (
                                    // eslint-disable-next-line @next/next/no-img-element
                                    <img src={item.imageUrl} alt={item.judul} 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>
                                )}
                            </div>
                            {/* Content */}
                            <div className="p-4 flex-1 flex flex-col">
                                <h3 className="font-bold text-slate-800 leading-tight mb-2 line-clamp-2">{item.judul}</h3>
                                <p className="text-xs text-slate-500 leading-relaxed line-clamp-3 flex-1">{item.narasi}</p>
                                <div className="flex items-center gap-1.5 mt-3 pt-3 border-t border-slate-100 text-xs text-slate-400">
                                    <Clock className="w-3 h-3" />
                                    {format(new Date(item.createdAt), 'd MMMM yyyy', { locale: id })}
                                </div>
                            </div>
                            {/* Delete 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 line-clamp-1">Hapus "{item.judul}"?</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" /> Hapus</button>
                                    </div>
                                </div>
                            ) : (
                                <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-slate-100 flex items-center justify-center"><Newspaper className="w-4.5 h-4.5 text-slate-600" /></div>
                            <div className="flex-1">
                                <h3 className="text-base font-bold text-slate-800">{selectedItem ? 'Edit Berita' : 'Tambah Berita Baru'}</h3>
                                <p className="text-xs text-slate-400">Isi judul, narasi, dan foto berita</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">
                                <div>
                                    <label className={labelCls}>Judul Berita</label>
                                    <input {...form.register('judul')} placeholder="Judul artikel berita..." className={inputCls} />
                                </div>
                                <div>
                                    <label className={labelCls}>Narasi / Isi</label>
                                    <textarea {...form.register('narasi')} rows={5} placeholder="Isi berita selengkapnya..." className={`${inputCls} resize-none`} />
                                </div>
                                <div>
                                    <label className={labelCls}>Tanggal Terbit</label>
                                    <input type="date" {...form.register('createdAt')} className={inputCls} />
                                </div>
                                <div>
                                    <label className={labelCls}>Foto / Thumbnail</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">
                                        <ImageIcon className="w-6 h-6 text-slate-300" />
                                        <span className="text-xs text-slate-500">{imageFile ? imageFile.name : 'Klik untuk pilih foto'}</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>
    );
}
