'use client'

import { useState, useEffect } from 'react'
import { X, Save, Building2, MapPin, Phone, User, Map as MapIcon, Loader2, Info, Plus, Trash2, Briefcase } from 'lucide-react'
import { supabase } from '@/lib/supabase'
import { useRouter } from 'next/navigation'
import { showSwal } from '@/lib/swal'

interface PetugasInput {
    id?: string
    nama_petugas: string
    nomor_hp: string
    jabatan: string
}

interface PosyanduFormModalProps {
    isOpen: boolean
    onClose: () => void
    selectedData?: any | null
}

export function PosyanduFormModal({ isOpen, onClose, selectedData }: PosyanduFormModalProps) {
    const router = useRouter()
    const [loading, setLoading] = useState(false)
    const [formData, setFormData] = useState({
        nama_posyandu: '',
        alamat: '',
        kontak: '', // This stays as the Posyandu general contact if needed, but we'll prioritize petugas contacts
        link_google_maps: ''
    })
    const [petugas, setPetugas] = useState<PetugasInput[]>([
        { nama_petugas: '', nomor_hp: '', jabatan: 'Koordinator' }
    ])

    useEffect(() => {
        if (selectedData) {
            setFormData({
                nama_posyandu: selectedData.nama_posyandu || '',
                alamat: selectedData.alamat || '',
                kontak: selectedData.kontak || '',
                link_google_maps: selectedData.link_google_maps || ''
            })

            if (selectedData.petugas && selectedData.petugas.length > 0) {
                setPetugas(selectedData.petugas.map((p: any) => ({
                    id: p.id,
                    nama_petugas: p.nama_petugas || '',
                    nomor_hp: p.nomor_hp || '',
                    jabatan: p.jabatan || ''
                })))
            } else {
                setPetugas([{ nama_petugas: '', nomor_hp: '', jabatan: 'Koordinator' }])
            }
        } else {
            setFormData({
                nama_posyandu: '',
                alamat: '',
                kontak: '',
                link_google_maps: ''
            })
            setPetugas([{ nama_petugas: '', nomor_hp: '', jabatan: 'Koordinator' }])
        }
    }, [selectedData])

    const handleAddPetugas = () => {
        setPetugas([...petugas, { nama_petugas: '', nomor_hp: '', jabatan: '' }])
    }

    const handleRemovePetugas = (index: number) => {
        if (petugas.length === 1) {
            setPetugas([{ nama_petugas: '', nomor_hp: '', jabatan: 'Koordinator' }])
        } else {
            setPetugas(petugas.filter((_, i) => i !== index))
        }
    }

    const handlePetugasChange = (index: number, field: keyof PetugasInput, value: string) => {
        const updatedPetugas = [...petugas]
        updatedPetugas[index] = { ...updatedPetugas[index], [field]: value }
        setPetugas(updatedPetugas)
    }

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault()
        setLoading(true)

        try {
            const payload = {
                nama_posyandu: formData.nama_posyandu,
                alamat: formData.alamat,
                kontak: formData.kontak,
                link_google_maps: formData.link_google_maps
            }

            let posyanduId = selectedData?.id

            if (selectedData) {
                // Update Posyandu
                const { error } = await supabase.from('detail_posyandu').update(payload).eq('id', selectedData.id)
                if (error) throw error
            } else {
                // Insert Posyandu
                const { data, error } = await supabase.from('detail_posyandu').insert(payload).select().single()
                if (error) throw error
                posyanduId = data.id
            }
            // ... [Officer sync logic remains same] ...
            // Sync Petugas
            // 1. Get current IDs in DB for this Posyandu
            const { data: existingInDB } = await supabase
                .from('petugas_posyandu_lokal')
                .select('id')
                .eq('posyandu_id', posyanduId)

            const dbIds = existingInDB?.map(p => p.id) || []
            const currentFormIds = petugas.map(p => p.id).filter(Boolean) as string[]

            // 2. Identify deleted ones
            const idsToDelete = dbIds.filter(id => !currentFormIds.includes(id))
            if (idsToDelete.length > 0) {
                await supabase.from('petugas_posyandu_lokal').delete().in('id', idsToDelete)
            }

            // 3. Update or Insert
            for (const p of petugas) {
                // Skip if entirely empty
                if (!p.nama_petugas && !p.nomor_hp) continue

                const petugasPayload = {
                    posyandu_id: posyanduId,
                    nama_petugas: p.nama_petugas,
                    nomor_hp: p.nomor_hp,
                    jabatan: p.jabatan
                }

                if (p.id) {
                    // Update
                    await supabase.from('petugas_posyandu_lokal').update(petugasPayload).eq('id', p.id)
                } else {
                    // Insert
                    await supabase.from('petugas_posyandu_lokal').insert(petugasPayload)
                }
            }

            await showSwal.success('Berhasil!', 'Data Posyandu telah disimpan.')
            router.refresh()
            onClose()
        } catch (err: any) {
            showSwal.error('Gagal!', err.message)
        } finally {
            setLoading(false)
        }
    }

    if (!isOpen) return null

    return (
        <div className="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
            <div className="bg-white w-full max-w-2xl rounded-2xl border-2 border-black shadow-[12px_12px_0px_0px_rgba(0,0,0,1)] flex flex-col max-h-[90vh]">

                {/* Header */}
                <div className="flex items-center justify-between p-6 border-b-2 border-black bg-purple-600 text-white">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-white/20 rounded-lg">
                            <Building2 className="w-5 h-5 text-white" />
                        </div>
                        <div>
                            <h2 className="text-xl font-bold leading-none">
                                {selectedData ? 'Edit Data Posyandu' : 'Tambah Posyandu Baru'}
                            </h2>
                            <p className="text-[10px] text-purple-200 uppercase tracking-widest mt-1">OPERASIONAL POSYANDU</p>
                        </div>
                    </div>
                    <button onClick={onClose} className="p-2 hover:bg-white/10 rounded-full transition-colors">
                        <X className="w-5 h-5" />
                    </button>
                </div>

                {/* Form Body */}
                <form onSubmit={handleSubmit} className="p-6 overflow-y-auto flex flex-col gap-6">

                    {/* Informasi Dasar */}
                    <div className="flex flex-col gap-4">
                        <h3 className="text-sm font-black uppercase tracking-widest text-purple-600 border-b-2 border-purple-100 pb-2">Informasi Dasar</h3>
                        <div className="flex flex-col gap-2">
                            <label className="text-xs font-black uppercase tracking-widest text-gray-500 flex items-center gap-2">
                                <Building2 className="w-3.5 h-3.5" />
                                Nama Posyandu
                            </label>
                            <input
                                required
                                type="text"
                                placeholder="Contoh: Posyandu Melati 01"
                                value={formData.nama_posyandu}
                                onChange={e => setFormData({ ...formData, nama_posyandu: e.target.value })}
                                className="w-full px-4 py-3 bg-gray-50 border-2 border-gray-100 focus:border-black rounded-xl text-sm font-bold outline-none transition-all"
                            />
                        </div>

                        <div className="flex flex-col gap-2">
                            <label className="text-xs font-black uppercase tracking-widest text-gray-500 flex items-center gap-2">
                                <MapPin className="w-3.5 h-3.5" />
                                Alamat Lengkap
                            </label>
                            <textarea
                                required
                                rows={2}
                                placeholder="Jl. Raya No. 123..."
                                value={formData.alamat}
                                onChange={e => setFormData({ ...formData, alamat: e.target.value })}
                                className="w-full px-4 py-3 bg-gray-50 border-2 border-gray-100 focus:border-black rounded-xl text-sm font-bold outline-none transition-all resize-none"
                            />
                        </div>
                    </div>

                    {/* Section Petugas */}
                    <div className="flex flex-col gap-4">
                        <div className="flex items-center justify-between border-b-2 border-purple-100 pb-2">
                            <h3 className="text-sm font-black uppercase tracking-widest text-purple-600">Petugas Posyandu</h3>
                            <button
                                type="button"
                                onClick={handleAddPetugas}
                                className="flex items-center gap-1.5 px-3 py-1.5 bg-purple-50 text-purple-600 rounded-lg text-[10px] font-black hover:bg-purple-100 transition-all border border-purple-200"
                            >
                                <Plus className="w-3 h-3" />
                                TAMBAH PETUGAS
                            </button>
                        </div>

                        <div className="flex flex-col gap-4">
                            {petugas.map((p, index) => (
                                <div key={index} className="p-4 bg-gray-50/50 rounded-2xl border-2 border-gray-100 relative group animate-in fade-in slide-in-from-top-2">
                                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                                        <div className="flex flex-col gap-1.5">
                                            <label className="text-[10px] font-black uppercase text-gray-400 tracking-wider flex items-center gap-1.5">
                                                <User className="w-3 h-3" /> Nama Petugas
                                            </label>
                                            <input
                                                required
                                                type="text"
                                                placeholder="Nama"
                                                value={p.nama_petugas}
                                                onChange={e => handlePetugasChange(index, 'nama_petugas', e.target.value)}
                                                className="w-full px-3 py-2 bg-white border-2 border-gray-100 focus:border-purple-500 rounded-lg text-xs font-bold outline-none transition-all"
                                            />
                                        </div>
                                        <div className="flex flex-col gap-1.5">
                                            <label className="text-[10px] font-black uppercase text-gray-400 tracking-wider flex items-center gap-1.5">
                                                <Phone className="w-3 h-3" /> No. HP
                                            </label>
                                            <input
                                                type="text"
                                                placeholder="0812xxxx"
                                                value={p.nomor_hp}
                                                onChange={e => handlePetugasChange(index, 'nomor_hp', e.target.value)}
                                                className="w-full px-3 py-2 bg-white border-2 border-gray-100 focus:border-purple-500 rounded-lg text-xs font-bold outline-none transition-all"
                                            />
                                        </div>
                                        <div className="flex flex-col gap-1.5">
                                            <label className="text-[10px] font-black uppercase text-gray-400 tracking-wider flex items-center gap-1.5">
                                                <Briefcase className="w-3 h-3" /> Jabatan
                                            </label>
                                            <input
                                                type="text"
                                                placeholder="Contoh: Koordinator"
                                                value={p.jabatan}
                                                onChange={e => handlePetugasChange(index, 'jabatan', e.target.value)}
                                                className="w-full px-3 py-2 bg-white border-2 border-gray-100 focus:border-purple-500 rounded-lg text-xs font-bold outline-none transition-all"
                                            />
                                        </div>
                                    </div>
                                    {petugas.length > 1 && (
                                        <button
                                            type="button"
                                            onClick={() => handleRemovePetugas(index)}
                                            className="absolute -right-2 -top-2 p-1.5 bg-white border-2 border-red-100 text-red-500 rounded-full hover:bg-red-50 transition-all shadow-sm md:opacity-0 md:group-hover:opacity-100"
                                        >
                                            <Trash2 className="w-3.5 h-3.5" />
                                        </button>
                                    )}
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* Google Maps Section */}
                    <div className="p-4 bg-blue-50/50 rounded-2xl border-2 border-blue-100 flex flex-col gap-4">
                        <div className="flex items-center gap-2 text-blue-700">
                            <MapIcon className="w-4 h-4" />
                            <span className="text-xs font-bold uppercase tracking-widest">Titik Lokasi Google Maps</span>
                        </div>

                        <div className="flex flex-col gap-2">
                            <label className="text-[10px] font-black uppercase text-blue-400 tracking-wider">Link Google Maps (Pasti kan link ini benar)</label>
                            <input
                                type="url"
                                placeholder="https://maps.app.goo.gl/..."
                                value={formData.link_google_maps}
                                onChange={e => setFormData({ ...formData, link_google_maps: e.target.value })}
                                className="w-full px-4 py-3 bg-white border-2 border-blue-100 focus:border-blue-500 rounded-xl text-xs font-bold outline-none transition-all"
                            />
                        </div>

                        <div className="flex items-start gap-2 text-[10px] text-blue-500 leading-relaxed italic">
                            <Info className="w-3 h-3 mt-0.5 flex-shrink-0" />
                            <span>Cantumkan link Google Maps agar admin lain dapat melihat lokasi dengan mudah di web.</span>
                        </div>
                    </div>

                    {/* Footer Actions */}
                    <div className="flex items-center gap-3 mt-2">
                        <button
                            type="button"
                            onClick={onClose}
                            className="flex-1 py-3 border-2 border-black rounded-xl font-bold text-sm hover:bg-gray-50 transition-all"
                        >
                            Batal
                        </button>
                        <button
                            type="submit"
                            disabled={loading}
                            className="flex-[2] py-3 bg-black text-white font-black text-sm rounded-xl hover:bg-gray-800 transition-all flex items-center justify-center gap-2 shadow-[4px_4px_0px_0px_rgba(147,51,234,0.5)]"
                        >
                            {loading ? (
                                <Loader2 className="w-4 h-4 animate-spin" />
                            ) : (
                                <Save className="w-4 h-4" />
                            )}
                            Simpan Data
                        </button>
                    </div>
                </form>
            </div>
        </div>
    )
}
