'use client';

import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import { GaleriSchema } from '@/lib/validations';
import { createGaleri } from '@/lib/admin-actions';
import { uploadImage } from '@/lib/upload';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

type GaleriFormValues = z.infer<typeof GaleriSchema>;

export default function GaleriForm({
    isOpen,
    setIsOpen,
}: {
    isOpen: boolean;
    setIsOpen: (val: boolean) => void;
}) {
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [imageFile, setImageFile] = useState<File | null>(null);
    const [photoLinks, setPhotoLinks] = useState<string[]>(['']);

    const form = useForm<GaleriFormValues>({
        resolver: zodResolver(GaleriSchema),
        defaultValues: {
            judul: '',
            imageUrl: 'https://images.unsplash.com/photo-1542435503-956c469947f6',
            driveUrl: '',
            createdAt: new Date().toISOString().split('T')[0],
        },
    });

    const onSubmit = async (values: GaleriFormValues) => {
        if (!imageFile) {
            toast.error('Harap pilih dan unggah file gambar terlebih dahulu!');
            return;
        }
        setIsSubmitting(true);
        try {
            const finalImgUrl = await uploadImage(imageFile);
            const payload = {
                judul: values.judul,
                imageUrl: finalImgUrl,
                driveUrl: values.driveUrl,
                photos: photoLinks.filter(link => link.trim() !== ''),
                createdAt: values.createdAt ? new Date(values.createdAt) : new Date(),
            };

            // Galeri hanya create & delete sesuai instruksi awal
            const result = await createGaleri(payload);

            if (result.success) {
                toast.success(result.message);
                setIsOpen(false);
                form.reset();
                setImageFile(null);
                setPhotoLinks(['']);
            } else {
                toast.error(result.message);
            }
        } catch (e: any) {
            toast.error('Gagal memproses upload', { description: e.message });
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <Dialog open={isOpen} onOpenChange={setIsOpen}>
            <DialogContent className="max-w-md">
                <DialogHeader>
                    <DialogTitle>Unggah Foto Baru</DialogTitle>
                </DialogHeader>
                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                    <div className="space-y-2">
                        <Label>Judul / Keterangan Foto</Label>
                        <Input {...form.register('judul')} placeholder="Keterangan gambar..." />
                        {form.formState.errors.judul && (
                            <p className="text-sm text-red-500">{form.formState.errors.judul.message}</p>
                        )}
                    </div>

                    <div className="space-y-2">
                        <Label>Link Google Drive (Folder/Opsional)</Label>
                        <Input {...form.register('driveUrl')} placeholder="https://drive.google.com/..." />
                    </div>

                    <div className="space-y-2">
                        <Label>Daftar Foto Google Drive (Preview)</Label>
                        {photoLinks.map((link, index) => (
                            <div key={index} className="flex gap-2 mb-2">
                                <Input
                                    value={link}
                                    onChange={(e) => {
                                        const newLinks = [...photoLinks];
                                        newLinks[index] = e.target.value;
                                        setPhotoLinks(newLinks);
                                    }}
                                    placeholder="https://drive.google.com/file/d/..."
                                />
                                {index > 0 && (
                                    <Button
                                        type="button"
                                        variant="destructive"
                                        size="icon"
                                        onClick={() => {
                                            const newLinks = photoLinks.filter((_, i) => i !== index);
                                            setPhotoLinks(newLinks);
                                        }}
                                    >
                                        <span className="text-xl leading-none">&times;</span>
                                    </Button>
                                )}
                            </div>
                        ))}
                        <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => setPhotoLinks([...photoLinks, ''])}
                            className="mt-2 w-full"
                        >
                            + Tambah Foto Lain
                        </Button>
                    </div>

                    <div className="space-y-2">
                        <Label>Tanggal Posting</Label>
                        <Input type="date" {...form.register('createdAt')} />
                    </div>

                    <div className="space-y-2">
                        <Label>Pilih Gambar (Wajib)</Label>
                        <Input type="file" accept="image/*" required onChange={(e) => setImageFile(e.target.files?.[0] || null)} />
                        <p className="text-xs text-muted-foreground">Pilih file gambar berformat PNG, JPG, JPEG, atau WebP.</p>
                    </div>

                    <Button type="submit" className="w-full" disabled={isSubmitting}>
                        {isSubmitting ? 'Mengunggah...' : 'Unggah ke Galeri'}
                    </Button>
                </form>
            </DialogContent>
        </Dialog>
    );
}
