'use client';

import { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import { PengurusSchema } from '@/lib/validations';
import { createPengurus, updatePengurus } from '@/lib/admin-actions';
import { uploadImage } from '@/lib/upload';
import { z } from 'zod';
import { X, UserCircle2, Upload, Loader2 } from 'lucide-react';

type PengurusFormValues = z.infer<typeof PengurusSchema>;

export default function PengurusForm({
    isOpen,
    setIsOpen,
    initialData,
    bidangLembagaList = [],
}: {
    isOpen: boolean;
    setIsOpen: (val: boolean) => void;
    initialData?: any;
    bidangLembagaList?: any[];
}) {
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [imageFile, setImageFile] = useState<File | null>(null);
    const [imagePreview, setImagePreview] = useState<string | null>(null);

    const getInitialValues = () => {
        if (!initialData) {
            return {
                nama: '',
                npm: '',
                jabatan: '',
                divisi: '',
                angkatan: '',
                fotoUrl: 'https://images.unsplash.com/photo-1599566150163-29194dcaad36',
                linkedinUrl: '',
                instagramUrl: '',
            };
        }
        let formJabatan = '';
        if (initialData.jabatan === 'Ketua Himpunan') {
            formJabatan = 'KETUA_HIMPUNAN';
        } else if (initialData.jabatan === 'Wakil Ketua Himpunan') {
            formJabatan = 'WAKIL_KETUA_HIMPUNAN';
        } else if (initialData.jabatan === 'Ketua Bidang' || initialData.jabatan === 'Ketua Lembaga') {
            formJabatan = 'KETUA';
        } else if (initialData.jabatan === 'Wakil Ketua Bidang' || initialData.jabatan === 'Wakil Ketua Lembaga') {
            formJabatan = 'WAKIL_KETUA';
        } else if (initialData.jabatan === 'Staf Bidang' || initialData.jabatan === 'Staf Lembaga') {
            formJabatan = 'STAF';
        } else {
            formJabatan = initialData.jabatan;
        }
        return {
            ...initialData,
            jabatan: formJabatan,
            linkedinUrl: initialData.linkedinUrl || '',
            instagramUrl: initialData.instagramUrl || '',
        };
    };

    const form = useForm<PengurusFormValues>({
        resolver: zodResolver(PengurusSchema),
        defaultValues: getInitialValues(),
    });

    const selectedJabatan = form.watch('jabatan');
    const isKahimOrWakahim = selectedJabatan === 'KETUA_HIMPUNAN' || selectedJabatan === 'WAKIL_KETUA_HIMPUNAN';

    useEffect(() => {
        if (isKahimOrWakahim) {
            form.setValue('divisi', 'Pengurus Harian');
        } else if (form.getValues('divisi') === 'Pengurus Harian') {
            form.setValue('divisi', '');
        }
    }, [isKahimOrWakahim, form]);

    const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0] || null;
        setImageFile(file);
        if (file) {
            const reader = new FileReader();
            reader.onloadend = () => setImagePreview(reader.result as string);
            reader.readAsDataURL(file);
        } else {
            setImagePreview(null);
        }
    };

    const onSubmit = async (values: PengurusFormValues) => {
        setIsSubmitting(true);
        try {
            let finalFotoUrl = values.fotoUrl;
            if (imageFile) {
                finalFotoUrl = await uploadImage(imageFile);
            }

            let finalJabatan = values.jabatan;
            let finalDivisi = values.divisi;

            if (values.jabatan === 'KETUA_HIMPUNAN') {
                finalJabatan = 'Ketua Himpunan';
                finalDivisi = 'Pengurus Harian';
            } else if (values.jabatan === 'WAKIL_KETUA_HIMPUNAN') {
                finalJabatan = 'Wakil Ketua Himpunan';
                finalDivisi = 'Pengurus Harian';
            } else {
                const selectedDiv = bidangLembagaList.find(d => d.name === values.divisi || d.slug === values.divisi);
                const isLembaga = selectedDiv ? (selectedDiv.name.toLowerCase().includes('lembaga') || selectedDiv.slug.toLowerCase().includes('lembaga')) : false;

                if (values.jabatan === 'KETUA') {
                    finalJabatan = isLembaga ? 'Ketua Lembaga' : 'Ketua Bidang';
                } else if (values.jabatan === 'WAKIL_KETUA') {
                    finalJabatan = isLembaga ? 'Wakil Ketua Lembaga' : 'Wakil Ketua Bidang';
                } else if (values.jabatan === 'STAF') {
                    finalJabatan = isLembaga ? 'Staf Lembaga' : 'Staf Bidang';
                }
            }

            const payload = {
                ...values,
                fotoUrl: finalFotoUrl,
                jabatan: finalJabatan,
                divisi: finalDivisi,
            };

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

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

    if (!isOpen) return null;

    const currentPhoto = imagePreview || initialData?.fotoUrl;

    return (
        <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">
                {/* Header */}
                <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-[#1e3a5f]/10 flex items-center justify-center flex-shrink-0">
                        <UserCircle2 className="h-5 w-5 text-[#1e3a5f]" />
                    </div>
                    <div>
                        <h3 className="text-lg font-bold text-slate-800">
                            {initialData ? 'Ubah Data Pengurus' : 'Tambah Pengurus Baru'}
                        </h3>
                        <p className="text-xs text-slate-400">
                            {initialData ? `Mengedit data ${initialData.nama}` : 'Isi informasi pengurus baru'}
                        </p>
                    </div>
                    <button
                        type="button"
                        onClick={() => setIsOpen(false)}
                        className="ml-auto p-1.5 rounded-xl hover:bg-slate-100 text-slate-400 hover:text-slate-600 transition-colors"
                    >
                        <X className="h-5 w-5" />
                    </button>
                </div>

                {/* Body */}
                <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-5">

                        {/* Section 1: Informasi Dasar */}
                        <div>
                            <p className="text-xs font-bold text-slate-400 uppercase tracking-widest mb-3 pb-1.5 border-b border-slate-100">
                                Informasi Dasar
                            </p>
                            <div className="space-y-4">
                                {/* Nama */}
                                <div>
                                    <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1.5">
                                        Nama Lengkap <span className="text-red-400">*</span>
                                    </label>
                                    <input
                                        {...form.register('nama')}
                                        placeholder="Contoh: Budi Santoso"
                                        className="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"
                                    />
                                    {form.formState.errors.nama && (
                                        <p className="text-xs text-red-500 mt-1">{form.formState.errors.nama.message}</p>
                                    )}
                                </div>
                                {/* Angkatan */}
                                <div className="space-y-1.5">
                                    <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1.5">
                                        Angkatan <span className="text-red-400">*</span>
                                    </label>
                                    <input
                                        {...form.register('angkatan')}
                                        placeholder="2021"
                                        className="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"
                                    />
                                    {form.formState.errors.angkatan && (
                                        <p className="text-xs text-red-500 mt-1">{form.formState.errors.angkatan.message}</p>
                                    )}
                                </div>
                            </div>
                        </div>

                        {/* Section 2: Jabatan & Divisi */}
                        <div>
                            <p className="text-xs font-bold text-slate-400 uppercase tracking-widest mb-3 pb-1.5 border-b border-slate-100">
                                Jabatan &amp; Divisi
                            </p>
                            <div className="space-y-4">
                                {/* Jabatan */}
                                <div>
                                    <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1.5">
                                        Jabatan <span className="text-red-400">*</span>
                                    </label>
                                    <select
                                        {...form.register('jabatan', { required: true })}
                                        className="w-full px-3.5 py-2.5 rounded-lg border border-slate-200 text-sm text-slate-800 focus:outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-400/10 transition-all bg-white"
                                    >
                                        <option value="">Pilih Jabatan...</option>
                                        <option value="KETUA_HIMPUNAN">Ketua Himpunan</option>
                                        <option value="WAKIL_KETUA_HIMPUNAN">Wakil Ketua Himpunan</option>
                                        <option value="KETUA">Ketua Bidang / Lembaga</option>
                                        <option value="WAKIL_KETUA">Wakil Ketua Bidang / Lembaga</option>
                                        <option value="STAF">Staf Bidang / Lembaga</option>
                                    </select>
                                    {form.formState.errors.jabatan && (
                                        <p className="text-xs text-red-500 mt-1">{form.formState.errors.jabatan.message}</p>
                                    )}
                                </div>

                                {/* Divisi - conditional */}
                                {!isKahimOrWakahim && (
                                    <div>
                                        <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1.5">
                                            Divisi / Bidang / Lembaga <span className="text-red-400">*</span>
                                        </label>
                                        <select
                                            {...form.register('divisi', { required: !isKahimOrWakahim })}
                                            className="w-full px-3.5 py-2.5 rounded-lg border border-slate-200 text-sm text-slate-800 focus:outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-400/10 transition-all bg-white"
                                        >
                                            <option value="">Pilih Divisi...</option>
                                            {bidangLembagaList.map((dept: any) => (
                                                <option key={dept.slug} value={dept.name}>
                                                    {dept.name}
                                                </option>
                                            ))}
                                        </select>
                                        {form.formState.errors.divisi && (
                                            <p className="text-xs text-red-500 mt-1">{form.formState.errors.divisi.message}</p>
                                        )}
                                    </div>
                                )}
                                {isKahimOrWakahim && (
                                    <div className="flex items-center gap-2 px-3.5 py-2.5 rounded-lg border border-slate-200 bg-slate-50">
                                        <span className="text-xs text-slate-400">Divisi otomatis:</span>
                                        <span className="text-sm font-medium text-slate-600">Pengurus Harian</span>
                                    </div>
                                )}
                            </div>
                        </div>

                        {/* Section 3: Media & Sosial */}
                        <div>
                            <p className="text-xs font-bold text-slate-400 uppercase tracking-widest mb-3 pb-1.5 border-b border-slate-100">
                                Media &amp; Sosial
                            </p>
                            <div className="space-y-4">
                                {/* Foto upload */}
                                <div>
                                    <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1.5">
                                        Foto Profil
                                    </label>
                                    <div className="flex items-center gap-4">
                                        {/* Preview circle */}
                                        <div className="flex-shrink-0">
                                            {currentPhoto ? (
                                                <img
                                                    src={currentPhoto}
                                                    alt="Preview"
                                                    className="w-16 h-16 rounded-full object-cover border-2 border-slate-200"
                                                />
                                            ) : (
                                                <div className="w-16 h-16 rounded-full border-2 border-dashed border-slate-200 bg-slate-50 flex items-center justify-center">
                                                    <UserCircle2 className="h-7 w-7 text-slate-300" />
                                                </div>
                                            )}
                                        </div>
                                        {/* Upload area */}
                                        <label className="flex-1 border-2 border-dashed border-slate-200 rounded-xl p-3 text-center hover:border-blue-300 hover:bg-blue-50/50 transition-all cursor-pointer">
                                            <Upload className="h-4 w-4 text-slate-400 mx-auto mb-1" />
                                            <p className="text-xs text-slate-500 font-medium">
                                                {imageFile ? imageFile.name : 'Klik untuk upload foto'}
                                            </p>
                                            <p className="text-xs text-slate-400 mt-0.5">PNG, JPG, WEBP maks. 5MB</p>
                                            <input
                                                type="file"
                                                accept="image/*"
                                                className="hidden"
                                                onChange={handleImageChange}
                                            />
                                        </label>
                                    </div>
                                    <p className="text-xs text-slate-400 mt-1.5">Biarkan kosong untuk tetap menggunakan foto saat ini.</p>
                                </div>

                                {/* LinkedIn */}
                                <div>
                                    <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1.5">
                                        LinkedIn URL
                                    </label>
                                    <input
                                        {...form.register('linkedinUrl')}
                                        placeholder="https://linkedin.com/in/username"
                                        className="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"
                                    />
                                    {form.formState.errors.linkedinUrl && (
                                        <p className="text-xs text-red-500 mt-1">{form.formState.errors.linkedinUrl.message}</p>
                                    )}
                                </div>

                                {/* Instagram */}
                                <div>
                                    <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1.5">
                                        Instagram URL
                                    </label>
                                    <input
                                        {...form.register('instagramUrl')}
                                        placeholder="https://instagram.com/username"
                                        className="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"
                                    />
                                    {form.formState.errors.instagramUrl && (
                                        <p className="text-xs text-red-500 mt-1">{form.formState.errors.instagramUrl.message}</p>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Footer */}
                    <div className="px-6 py-4 border-t border-slate-100 flex gap-3 justify-end bg-white">
                        <button
                            type="button"
                            onClick={() => setIsOpen(false)}
                            className="border border-slate-200 text-slate-600 px-4 py-2 rounded-lg text-sm hover:bg-slate-50 transition-colors"
                        >
                            Batal
                        </button>
                        <button
                            type="submit"
                            disabled={isSubmitting}
                            className="bg-[#1e3a5f] text-white px-6 py-2 rounded-lg text-sm font-semibold hover:bg-[#1e3a5f]/90 transition-colors disabled:opacity-60 flex items-center gap-2"
                        >
                            {isSubmitting && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
                            {isSubmitting ? 'Menyimpan...' : initialData ? 'Simpan Perubahan' : 'Tambah Pengurus'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}
