"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 GreenfeeWasher() {
    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/greenfee/drafts`)
            .then(res => res.json())
            .then(data => {
                const editableDrafts = data.map((f: any) => {
                    // JSONB fra Postgres kan noen ganger komme som en streng, 
                    // vi må sikre at vi parser det hvis det trengs
                    let parsedDraft = f.greenfee_draft;
                    if (typeof parsedDraft === 'string') {
                        try { parsedDraft = JSON.parse(parsedDraft); } 
                        catch (e) { console.error("Kunne ikke parse JSON", e); }
                    }

                    // Hent ut selve listen (fallback til tom liste hvis noe er feil)
                    const greenfeeList = parsedDraft?.foreslatt_greenfee || [];

                    return {
                        ...f,
                        greenfee_draft: parsedDraft, // Lagre den parsede versjonen for visning
                        edit_greenfee: greenfeeList  // Dette er arrayet som binder seg til input-feltene
                    };
                });
                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 removeRow = (facilityId: number, rowIndex: number) => {
        setDrafts(drafts.map(d => {
            if (d.id === facilityId) {
                const newRows = [...d.edit_greenfee];
                newRows.splice(rowIndex, 1);
                return { ...d, edit_greenfee: newRows };
            }
            return d;
        }));
    };

    const updateField = (facilityId: number, rowIndex: number, field: string, value: string | number) => {
        setDrafts(drafts.map(d => {
            if (d.id === facilityId) {
                const newRows = [...d.edit_greenfee];
                newRows[rowIndex] = { ...newRows[rowIndex], [field]: value };
                return { ...d, edit_greenfee: newRows };
            }
            return d;
        }));
    };

    const handleApprove = async () => {
        const toApprove = drafts.filter(d => selectedIds.includes(d.id)).map(d => ({
            facility_id: d.id,
            greenfee: d.edit_greenfee.map((row: any) => ({
                banenavn: row.banenavn || "",
                priskategori: row.priskategori || "",
                pris_voksne: Number(row.pris_voksne) || null,
                pris_junior: Number(row.pris_junior) || null
            }))
        }));

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

        setSaving(true);
        try {
            const res = await adminFetch(`${API_URL}/admin/greenfee/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 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">Greenfee-Vaskeriet</h1>
                        <p className="text-sm text-gray-600 mt-2">Sjekk at prisene gir mening før publisering.</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">Alt er rent og pent!</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.greenfee_url?.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.greenfee_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.greenfee_draft.ai_begrunnelse}
                                            </div>
                                        )}
                                        
                                        {draft.greenfee_draft?.foreslatt_avtaleklubber?.length > 0 && (
                                            <div className="bg-green-50/50 p-4 rounded-xl text-sm text-green-900 border border-green-100">
                                                <strong>🤝 AI fant disse avtaleklubbene i teksten:</strong> {draft.greenfee_draft.foreslatt_avtaleklubber.join(', ')}
                                            </div>
                                        )}

                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                                            <div>
                                                <h4 className="text-xs font-black uppercase tracking-widest text-gray-400 mb-2">Slik ser det ut i databasen nå:</h4>
                                                <div className="bg-gray-50 p-4 rounded-xl text-xs space-y-2 opacity-75">
                                                    {draft.greenfee && draft.greenfee.length > 0 ? draft.greenfee.map((g: any, i: number) => (
                                                        <div key={i} className="flex justify-between border-b pb-1">
                                                            <span>{g.banenavn} - {g.priskategori}</span>
                                                            <span className="font-bold">V: {g.pris_voksne || '-'} | J: {g.pris_junior || '-'}</span>
                                                        </div>
                                                    )) : "Ingen priser registrert."}
                                                </div>
                                            </div>
                                            
                                            <div>
                                                <h4 className="text-xs font-black uppercase tracking-widest text-green-600 mb-2">Nytt forslag å godkjenne:</h4>
                                                <div className="space-y-2">
                                                    {draft.edit_greenfee && draft.edit_greenfee.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,1.2fr)_minmax(0,1.2fr)_110px_110px_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.banenavn || ''} onChange={e => updateField(draft.id, idx, 'banenavn', e.target.value)} placeholder="Bane" />
                                                            <input className="w-full rounded border border-gray-100 p-2 text-xs outline-none focus:border-[#8bc34a]" value={row.priskategori || ''} onChange={e => updateField(draft.id, idx, 'priskategori', e.target.value)} placeholder="Kategori" />
                                                            <input className="w-full rounded border border-gray-100 p-2 text-center text-xs outline-none focus:border-[#8bc34a]" type="number" value={row.pris_voksne || ''} onChange={e => updateField(draft.id, idx, 'pris_voksne', e.target.value)} placeholder="Voksen" />
                                                            <input className="w-full rounded border border-gray-100 p-2 text-center text-xs outline-none focus:border-[#8bc34a]" type="number" value={row.pris_junior || ''} onChange={e => updateField(draft.id, idx, 'pris_junior', e.target.value)} placeholder="Junior" />
                                                            <button onClick={() => removeRow(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 rad">✕</button>
                                                        </div>
                                                    ))}
                                                    <button onClick={() => {
                                                        const newDrafts = [...drafts];
                                                        const draftIndex = newDrafts.findIndex(d => d.id === draft.id);
                                                        newDrafts[draftIndex].edit_greenfee.push({ banenavn: '', priskategori: '', pris_voksne: '', pris_junior: '' });
                                                        setDrafts(newDrafts);
                                                    }} className="text-xs font-bold text-[#8bc34a] hover:underline mt-2 inline-block">
                                                        + Legg til manuell rad
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
}
