'use client';

import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { createPrestasi, updatePrestasi, deletePrestasi } 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 { Textarea } from '@/components/ui/textarea';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Edit, Trash2, Plus, Trophy } from 'lucide-react';
import { format } from 'date-fns';
import { id } from 'date-fns/locale';

export default function PrestasiTable({ 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 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);
        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);
        setIsFormOpen(true);
    };

    const handleDelete = async (itemId: string) => {
        if (!confirm('Yakin ingin menghapus prestasi ini?')) return;
        const res = await deletePrestasi(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.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 updatePrestasi(selectedItem.id, payload);
                if (res.success) {
                    toast.success(res.message);
                    setData((prev) => {
                        const updated = prev.map((d) => (d.id === selectedItem.id ? { ...d, ...payload } : d));
                        return updated.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
                    });
                    setIsFormOpen(false);
                } else {
                    toast.error(res.message);
                }
            } else {
                const res = await createPrestasi(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">
                    <Trophy className="h-6 w-6 text-primary" />
                    <h2 className="text-xl font-bold">Kelola Prestasi</h2>
                </div>
                <Button onClick={handleAdd} className="gap-2">
                    <Plus className="h-4 w-4" />
                    Tambah Prestasi
                </Button>
            </div>

            <div className="rounded-md border bg-card">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Judul</TableHead>
                            <TableHead className="max-w-[300px]">Narasi (Preview)</TableHead>
                            <TableHead>Gambar</TableHead>
                            <TableHead>Tanggal</TableHead>
                            <TableHead className="text-right">Aksi</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {data.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={5} className="text-center py-10 text-muted-foreground">
                                    Belum ada data prestasi.
                                </TableCell>
                            </TableRow>
                        ) : (
                            data.map((item) => (
                                <TableRow key={item.id}>
                                    <TableCell className="font-medium max-w-[200px] truncate">{item.judul}</TableCell>
                                    <TableCell className="max-w-[300px]">
                                        <p className="text-sm text-muted-foreground truncate">{item.narasi}</p>
                                    </TableCell>
                                    <TableCell>
                                        {item.imageUrl ? (
                                            <img
                                                src={item.imageUrl}
                                                alt={item.judul}
                                                className="h-10 w-16 object-cover rounded border"
                                            />
                                        ) : (
                                            <span className="text-xs text-muted-foreground">-</span>
                                        )}
                                    </TableCell>
                                    <TableCell className="text-sm text-muted-foreground">
                                        {format(new Date(item.createdAt), 'dd MMM yyyy', { locale: id })}
                                    </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">
                    <DialogHeader>
                        <DialogTitle>{selectedItem ? 'Edit Prestasi' : 'Tambah Prestasi Baru'}</DialogTitle>
                    </DialogHeader>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                        <div className="space-y-2">
                            <Label>Judul Prestasi <span className="text-destructive">*</span></Label>
                            <Input
                                {...form.register('judul', { required: true })}
                                placeholder="Masukkan judul prestasi..."
                            />
                        </div>
                        <div className="space-y-2">
                            <Label>Narasi / Deskripsi <span className="text-destructive">*</span></Label>
                            <Textarea
                                {...form.register('narasi', { required: true })}
                                placeholder="Ceritakan pencapaian prestasi ini..."
                                rows={5}
                            />
                        </div>
                        <div className="space-y-2">
                            <Label>Tanggal Posting</Label>
                            <Input
                                type="date"
                                {...form.register('createdAt')}
                            />
                        </div>
                        <div className="space-y-2">
                            <Label>Unggah Gambar</Label>
                            {selectedItem && selectedItem.imageUrl && (
                                <div className="mb-2">
                                    <p className="text-xs text-muted-foreground mb-1">Gambar saat ini:</p>
                                    <img src={selectedItem.imageUrl} className="h-20 w-32 object-cover rounded 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 Prestasi'}
                            </Button>
                        </div>
                    </form>
                </DialogContent>
            </Dialog>
        </div>
    );
}
