'use client';

import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { createProdukMumas, updateProdukMumas, deleteProdukMumas } 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, FileText, Download } from 'lucide-react';
import { format } from 'date-fns';
import { id } from 'date-fns/locale';

export default function ProdukMumasTable({ 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 [fileFile, setFileFile] = useState<File | null>(null);

    const form = useForm({
        defaultValues: { judul: '', kategori: 'Ketetapan' },
    });

    const handleAdd = () => {
        setSelectedItem(null);
        form.reset({ judul: '', kategori: 'Ketetapan' });
        setFileFile(null);
        setIsFormOpen(true);
    };

    const handleEdit = (item: any) => {
        setSelectedItem(item);
        form.reset({ 
            judul: item.judul, 
            kategori: item.kategori || 'Ketetapan',
        });
        setFileFile(null);
        setIsFormOpen(true);
    };

    const handleDelete = async (itemId: string) => {
        if (!confirm('Yakin ingin menghapus produk mumas ini?')) return;
        const res = await deleteProdukMumas(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 finalFileUrl = selectedItem ? selectedItem.fileUrl : '';
            if (fileFile) {
                // We reuse uploadImage as it works for any file via /api/upload
                finalFileUrl = await uploadImage(fileFile);
            } else if (!selectedItem && !fileFile) {
                toast.error("File dokumen wajib diunggah.");
                setIsSubmitting(false);
                return;
            }

            const payload = {
                judul: values.judul.trim(),
                kategori: values.kategori.trim(),
                fileUrl: finalFileUrl,
            };

            if (selectedItem) {
                const res = await updateProdukMumas(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 createProdukMumas(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">
                    <FileText className="h-6 w-6 text-primary" />
                    <h2 className="text-xl font-bold">Kelola Produk Mumas</h2>
                </div>
                <Button onClick={handleAdd} className="gap-2">
                    <Plus className="h-4 w-4" />
                    Tambah Produk
                </Button>
            </div>

            <div className="rounded-md border bg-card overflow-x-auto">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Judul</TableHead>
                            <TableHead>Kategori</TableHead>
                            <TableHead>File</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 produk mumas yang ditambahkan.
                                </TableCell>
                            </TableRow>
                        ) : (
                            data.map((item) => (
                                <TableRow key={item.id}>
                                    <TableCell className="font-medium">{item.judul}</TableCell>
                                    <TableCell>{item.kategori}</TableCell>
                                    <TableCell>
                                        {item.fileUrl ? (
                                            <a 
                                                href={item.fileUrl} 
                                                target="_blank" 
                                                rel="noreferrer"
                                                className="flex items-center gap-2 text-primary hover:underline"
                                            >
                                                <Download className="h-4 w-4" />
                                                <span>Unduh</span>
                                            </a>
                                        ) : (
                                            <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 Produk Mumas' : 'Tambah Produk Mumas'}</DialogTitle>
                    </DialogHeader>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                        <div className="space-y-2">
                            <Label>Judul <span className="text-destructive">*</span></Label>
                            <Input {...form.register('judul', { required: true })} placeholder="Judul Dokumen" />
                        </div>
                        <div className="space-y-2">
                            <Label>Kategori <span className="text-destructive">*</span></Label>
                            <Input {...form.register('kategori', { required: true })} placeholder="Contoh: Ketetapan, Rekomendasi, dll" />
                        </div>
                        <div className="space-y-2">
                            <Label>File Dokumen {!selectedItem && <span className="text-destructive">*</span>}</Label>
                            {selectedItem && selectedItem.fileUrl && (
                                <div className="mb-2">
                                    <p className="text-xs text-muted-foreground mb-1">File saat ini:</p>
                                    <a href={selectedItem.fileUrl} target="_blank" rel="noreferrer" className="text-sm text-primary hover:underline break-all">
                                        {selectedItem.fileUrl}
                                    </a>
                                </div>
                            )}
                            <Input
                                type="file"
                                onChange={(e) => {
                                    const file = e.target.files?.[0] || null;
                                    setFileFile(file);
                                }}
                            />
                            <p className="text-xs text-muted-foreground">Dapat mengunggah PDF atau dokumen lainnya.</p>
                        </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 Produk'}
                            </Button>
                        </div>
                    </form>
                </DialogContent>
            </Dialog>
        </div>
    );
}
