"use client";
import { useState, useEffect } from 'react';
import { API_URL } from "@/config/constants";
import { adminFetch } from "@/config/adminFetch";
import AdminMobileMenu from "@/components/AdminMobileMenu";
import Link from 'next/link';

export default function VtgWasher() {
    const [drafts, setDrafts] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [selectedIds, setSelectedIds] = useState<number[]>([]);
    const [saving, setSaving] = useState(false);

    const fetchDrafts = () => {
        setLoading(true);
        adminFetch(`${API_URL}/admin/vtg/drafts`)
            .then(res => res.json())
            .then(data => {
                const editableDrafts = data.map((f: any) => {
                    let parsedDraft = f.vtg_draft;
                    if (typeof parsedDraft === 'string') {
                        try { parsedDraft = JSON.parse(parsedDraft); } 
                        catch (e) { console.error("Kunne ikke parse JSON", e); }
                    }

                    return {
                        ...f,
                        vtg_draft: parsedDraft,
                        edit_pris: parsedDraft?.foreslatt_vtg_pris || f.vtg_pris || '',
                        edit_beskrivelse: parsedDraft?.foreslatt_vtg_beskrivelse || f.vtg_beskrivelse || '',
                        edit_datoer: parsedDraft?.foreslatt_vtg_datoer || []
                    };
                });
                setDrafts(editableDrafts);
                setLoading(false);
            })
            .catch(() => setLoading(false));
    };

    useEffect(() => { fetchDrafts(); }, []);

    const toggleSelectAll = (checked: boolean) => {
        if (checked) setSelectedIds(drafts.map(d => d.id));
        else setSelectedIds([]);
    };

    const toggleOne = (id: number) => {
        if (selectedIds.includes(id)) setSelectedIds(selectedIds.filter(i => i !== id));
        else setSelectedIds([...selectedIds, id]);
    };

    const updateField = (facilityId: number, field: string, value: any) => {
        setDrafts(drafts.map(d => d.id === facilityId ? { ...d, [field]: value } : d));
    };

    const updateDateRow = (facilityId: number, rowIndex: number, field: string, value: string) => {
        setDrafts(drafts.map(d => {
            if (d.id === facilityId) {
                const newDates = [...d.edit_datoer];
                newDates[rowIndex] = { ...newDates[rowIndex], [field]: value };
                return { ...d, edit_datoer: newDates };
            }
            return d;
        }));
    };

    const addDateRow = (facilityId: number) => {
        setDrafts(drafts.map(d => {
            if (d.id === facilityId) {
                return { ...d, edit_datoer: [...d.edit_datoer, { dato: '', status: 'Ledig' }] };
            }
            return d;
        }));
    };

    const removeDateRow = (facilityId: number, rowIndex: number) => {
        setDrafts(drafts.map(d => {
            if (d.id === facilityId) {
                const newDates = [...d.edit_datoer];
                newDates.splice(rowIndex, 1);
                return { ...d, edit_datoer: newDates };
            }
            return d;
        }));
    };

    const handleApprove = async () => {
        const toApprove = drafts.filter(d => selectedIds.includes(d.id)).map(d => ({
            facility_id: d.id,
            vtg_pris: Number(d.edit_pris) || null,
            vtg_beskrivelse: d.edit_beskrivelse,
            vtg_datoer: d.edit_datoer
        }));

        if (toApprove.length === 0) return alert("Velg minst ett anlegg å godkjenne.");

        setSaving(true);
        try {
            const res = await adminFetch(`${API_URL}/admin/vtg/approve-bulk`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ approvals: toApprove })
            });
            if (res.ok) {
                alert(`${toApprove.length} anlegg oppdatert!`);
                setSelectedIds([]);
                fetchDrafts();
            } else {
                alert("Noe gikk galt under lagring.");
            }
        } catch (e) {
            alert("Nettverksfeil");
        }
        setSaving(false);
    };

    if (loading) return <div className="p-20 text-center font-black animate-pulse">Laster VTG-utkast...</div>;

    return (
        <div className="min-h-screen bg-[#f1f7ed] p-8 text-[#11280f]">
            <div className="max-w-[1400px] mx-auto">
                <AdminMobileMenu />
                <div className="mb-10 flex flex-col gap-5 border-b border-gray-200 pb-6 md:flex-row md:items-end md:justify-between">
                    <div>
                        <Link href="/admin" className="text-sm font-bold text-gray-500 hover:text-[#8bc34a] mb-2 block">← Tilbake til oversikten</Link>
                        <h1 className="text-4xl font-black">VTG-Vaskeriet</h1>
                        <p className="text-sm text-gray-600 mt-2">Gå gjennom og godkjenn kursinformasjon for Veien til Golf.</p>
                    </div>
                    <button onClick={handleApprove} disabled={saving || selectedIds.length === 0} className="w-full rounded-xl bg-[#8bc34a] px-8 py-4 font-black uppercase tracking-widest text-white shadow-lg transition-all hover:scale-105 disabled:opacity-50 md:w-auto">
                        {saving ? 'Lagrer...' : `Godkjenn Valgte (${selectedIds.length})`}
                    </button>
                </div>

                {drafts.length === 0 ? (
                    <div className="bg-white p-20 rounded-[2rem] text-center shadow-sm">
                        <span className="text-6xl mb-4 block">🧹</span>
                        <h2 className="text-2xl font-black text-gray-400">Ingen ventende VTG-utkast!</h2>
                    </div>
                ) : (
                    <div className="space-y-6">
                        <div className="bg-white p-4 rounded-2xl shadow-sm flex items-center gap-4">
                            <input type="checkbox" className="w-5 h-5 accent-[#8bc34a] ml-2" checked={selectedIds.length === drafts.length && drafts.length > 0} onChange={(e) => toggleSelectAll(e.target.checked)} />
                            <span className="font-black uppercase tracking-widest text-xs text-gray-500">Velg Alle</span>
                        </div>

                        {drafts.map((draft, index) => (
                            <div key={draft.id} className={`p-6 rounded-3xl shadow-sm border-2 transition-all ${selectedIds.includes(draft.id) ? 'border-[#8bc34a] bg-[#8bc34a]/10 ring-2 ring-[#8bc34a]/20' : index % 2 === 0 ? 'border-[#e3edd7] bg-white' : 'border-[#dbe7f5] bg-[#f8fbff]'}`}>
                                <div className="flex gap-6 items-start">
                                    <div className="pt-2"><input type="checkbox" className="w-6 h-6 accent-[#8bc34a] cursor-pointer" checked={selectedIds.includes(draft.id)} onChange={() => toggleOne(draft.id)} /></div>
                                    <div className="flex-grow space-y-4">
                                        <div className="flex flex-col gap-3 border-b pb-4 md:flex-row md:items-center md:justify-between">
                                            <h3 className="text-2xl font-black">{draft.name} <span className="text-xs font-mono font-bold bg-gray-100 text-gray-400 px-2 py-1 rounded-md">ID: {draft.id}</span></h3>
                                            <a href={draft.vtg_lenke?.split(',')[0]} target="_blank" className="inline-flex w-full items-center justify-center rounded-lg bg-blue-50 px-4 py-3 text-xs font-bold text-blue-600 hover:underline md:w-auto">Sjekk Nettside ↗</a>
                                        </div>

                                        {draft.vtg_draft?.ai_begrunnelse && (
                                            <div className="bg-blue-50/50 p-4 rounded-xl text-sm italic text-blue-900 border border-blue-100">
                                                <strong>🤖 AI Begrunnelse:</strong> {draft.vtg_draft.ai_begrunnelse}
                                            </div>
                                        )}

                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                                            {/* Pris & Beskrivelse */}
                                            <div className="space-y-4">
                                                <h4 className="text-xs font-black uppercase tracking-widest text-green-600">Pris & Beskrivelse</h4>
                                                <div>
                                                    <label className="text-[10px] font-bold text-gray-500 uppercase">Standardpris for Voksen (kr)</label>
                                                    <input className="w-full mt-1 p-3 rounded-xl border border-gray-200 text-sm focus:border-[#8bc34a] outline-none" type="number" value={draft.edit_pris} onChange={e => updateField(draft.id, 'edit_pris', e.target.value)} placeholder="Eks: 1990" />
                                                </div>
                                                <div>
                                                    <label className="text-[10px] font-bold text-gray-500 uppercase">Selgende tekst / Inkludert i kurset</label>
                                                    <textarea className="w-full mt-1 p-3 rounded-xl border border-gray-200 text-sm focus:border-[#8bc34a] outline-none resize-y" rows={5} value={draft.edit_beskrivelse} onChange={e => updateField(draft.id, 'edit_beskrivelse', e.target.value)} placeholder="Beskriv kurset..." />
                                                </div>
                                            </div>
                                            
                                            {/* Kursdatoer */}
                                            <div>
                                                <h4 className="text-xs font-black uppercase tracking-widest text-green-600 mb-4">Kursdatoer</h4>
                                                <div className="space-y-2">
                                                    {draft.edit_datoer.length === 0 ? (
                                                        <div className="p-4 bg-gray-50 rounded-xl text-sm text-gray-500 italic">Fant ingen spesifikke kursdatoer.</div>
                                                    ) : (
                                                        draft.edit_datoer.map((row: any, idx: number) => (
                                                            <div key={idx} className="grid gap-2 rounded-lg border border-gray-200 bg-white p-3 relative group sm:grid-cols-[minmax(0,1fr)_150px_auto] sm:items-center">
                                                                <input className="w-full rounded border border-gray-100 p-2 text-xs font-bold outline-none focus:border-[#8bc34a]" value={row.dato} onChange={e => updateDateRow(draft.id, idx, 'dato', e.target.value)} placeholder="F.eks: 12.-14. mai" />
                                                                <select className="w-full rounded border border-gray-100 p-2 text-xs outline-none focus:border-[#8bc34a] bg-white" value={row.status} onChange={e => updateDateRow(draft.id, idx, 'status', e.target.value)}>
                                                                    <option value="Ledig">Ledig</option>
                                                                    <option value="Fulltegnet">Fulltegnet</option>
                                                                    <option value="Venteliste">Venteliste</option>
                                                                    <option value="Få plasser">Få plasser</option>
                                                                </select>
                                                                <button onClick={() => removeDateRow(draft.id, idx)} className="px-2 text-left text-red-400 transition-colors hover:text-red-600 sm:text-center sm:opacity-0 sm:group-hover:opacity-100" title="Slett dato">✕</button>
                                                            </div>
                                                        ))
                                                    )}
                                                    <button onClick={() => addDateRow(draft.id)} className="text-xs font-bold text-[#8bc34a] hover:underline mt-2 inline-block">
                                                        + Legg til ny dato
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
}
