'use client';

import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import { ProkerSchema } from '@/lib/validations';
import { createProker, updateProker } from '@/lib/admin-actions';
import { KATEGORI_PROGRAM } from '@/lib/data-program-kerja';
import { z } from 'zod';
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 { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

type ProkerFormValues = z.infer<typeof ProkerSchema>;

export default function ProkerForm({
    isOpen,
    setIsOpen,
    initialData,
    slugBidang,
    pengurusList = [],
}: {
    isOpen: boolean;
    setIsOpen: (val: boolean) => void;
    initialData?: any;
    slugBidang: string;
    pengurusList?: any[];
}) {
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [selectedPics, setSelectedPics] = useState<string[]>(() => {
        if (initialData?.penanggungJawab) {
            try {
                return JSON.parse(initialData.penanggungJawab);
            } catch (e) {
                return [];
            }
        }
        return [];
    });

    const form = useForm<ProkerFormValues>({
        resolver: zodResolver(ProkerSchema),
        defaultValues: initialData
            ? {
                nama: initialData.nama || '',
                deskripsi: initialData.deskripsi || '',
                status: initialData.status || 'PLANNING',
                bidang: initialData.bidang || slugBidang,
                penanggungJawab: initialData.penanggungJawab || null,
            }
            : {
                nama: '',
                deskripsi: '',
                status: 'PLANNING',
                bidang: slugBidang,
                penanggungJawab: null,
            },
    });

    const onSubmit = async (values: ProkerFormValues) => {
        setIsSubmitting(true);
        try {
            const payload = {
                ...values,
                penanggungJawab: JSON.stringify(selectedPics)
            };

            let result;
            if (initialData?.id) {
                result = await updateProker(initialData.id, payload);
            } else {
                result = await createProker(payload);
            }

            if (result.success) {
                toast.success(result.message);
                setIsOpen(false);
                form.reset();
            } else {
                toast.error(result.message);
            }
        } catch (e: any) {
            toast.error('Gagal memproses form', { description: e.message });
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <Dialog open={isOpen} onOpenChange={setIsOpen}>
            <DialogContent className="max-w-md max-h-[90vh] overflow-y-auto">
                <DialogHeader>
                    <DialogTitle>{initialData ? 'Ubah Proker' : 'Tambah Proker'}</DialogTitle>
                </DialogHeader>
                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                    <div className="space-y-2">
                        <Label>Nama Program Kerja</Label>
                        <Input {...form.register('nama')} placeholder="Nama Proker" />
                        {form.formState.errors.nama && (
                            <p className="text-sm text-red-500">{form.formState.errors.nama.message}</p>
                        )}
                    </div>

                    <div className="space-y-2 hidden">
                        <Label>Bidang / Lembaga</Label>
                        <Input {...form.register('bidang')} type="hidden" />
                    </div>

                    <div className="space-y-2">
                        <Label>Deskripsi</Label>
                        <Textarea {...form.register('deskripsi')} rows={3} placeholder="Penjelasan mengenai program kerja..." />
                        {form.formState.errors.deskripsi && (
                            <p className="text-sm text-red-500">{form.formState.errors.deskripsi.message}</p>
                        )}
                    </div>

                    <div className="space-y-2">
                        <Label>Penanggung Jawab (PIC)</Label>
                        <div className="border rounded-md p-3 max-h-40 overflow-y-auto space-y-2 bg-card">
                            {pengurusList.length === 0 ? (
                                <p className="text-xs text-muted-foreground">Belum ada data pengurus di sistem.</p>
                            ) : (
                                pengurusList.map((p: any) => {
                                    const isChecked = selectedPics.includes(p.id);
                                    return (
                                        <label key={p.id} className="flex items-center gap-2 text-sm font-medium cursor-pointer hover:bg-muted/40 p-1.5 rounded transition-colors text-foreground">
                                            <input 
                                                type="checkbox" 
                                                checked={isChecked}
                                                onChange={(e) => {
                                                    if (e.target.checked) {
                                                        setSelectedPics(prev => [...prev, p.id]);
                                                    } else {
                                                        setSelectedPics(prev => prev.filter(id => id !== p.id));
                                                    }
                                                }}
                                                className="rounded border-gray-300 text-primary focus:ring-primary h-4 w-4"
                                            />
                                            <div className="flex items-center gap-2">
                                                <img src={p.fotoUrl} alt={p.nama} className="w-5.5 h-5.5 rounded-full object-cover border" />
                                                <div className="leading-tight">
                                                    <p className="font-bold text-xs">{p.nama}</p>
                                                    <p className="text-[10px] text-muted-foreground">{p.jabatan} ({p.divisi})</p>
                                                </div>
                                            </div>
                                        </label>
                                    );
                                })
                            )}
                        </div>
                    </div>

                    <div className="space-y-2">
                        <div className="space-y-2">
                            <Label>Status</Label>
                            <Select
                                onValueChange={(val) => form.setValue('status', val as any)}
                                defaultValue={form.getValues('status')}
                            >
                                <SelectTrigger>
                                    <SelectValue placeholder="Status Proker" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="PLANNING">Perencanaan</SelectItem>
                                    <SelectItem value="ONGOING">Sedang Berjalan</SelectItem>
                                    <SelectItem value="COMPLETED">Selesai</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                    </div>

                    <Button type="submit" className="w-full" disabled={isSubmitting}>
                        {isSubmitting ? 'Menyimpan...' : 'Simpan Proker'}
                    </Button>
                </form>
            </DialogContent>
        </Dialog>
    );
}
