"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { X } from "lucide-react";
import { useTheme } from "next-themes";

interface ConsentState {
    necessary: boolean;
    functional: boolean;
    analytics: boolean;
}

export default function CookieConsentModal() {
    const [isOpen, setIsOpen] = useState(false);
    const [showPreferences, setShowPreferences] = useState(false);
    const [consent, setConsent] = useState<ConsentState>({
        necessary: true,
        functional: true,
        analytics: false,
    });
    const { setTheme } = useTheme();

    useEffect(() => {
        // Check if consent is already saved
        const savedConsent = localStorage.getItem("cookie_consent");
        if (!savedConsent) {
            setIsOpen(true);
        } else {
            const parsed = JSON.parse(savedConsent);
            setConsent(parsed);

            // Enforce functional cookie logic on load
            if (!parsed.functional) {
                // If the user previously denied functional cookies, ensure theme is not persisted/active
                setTheme("light"); // Visual feedback
                localStorage.removeItem("theme");
            }
        }

        // Listener for opening from footer
        const handleOpenSettings = () => {
            setIsOpen(true);
            setShowPreferences(true);
        };

        window.addEventListener("open-cookie-settings", handleOpenSettings);
        return () => window.removeEventListener("open-cookie-settings", handleOpenSettings);
    }, [setTheme]);

    const handleAcceptAll = () => {
        const allConsent = {
            necessary: true,
            functional: true,
            analytics: true,
        };
        saveConsent(allConsent);
    };

    const handleSavePreferences = () => {
        saveConsent(consent);
    };

    const saveConsent = (settings: ConsentState) => {
        localStorage.setItem("cookie_consent", JSON.stringify(settings));
        window.dispatchEvent(new Event("cookie-consent-updated"));
        setConsent(settings);
        setIsOpen(false);

        // Handle Analytics
        if (settings.analytics) {
            console.log("Analytics cookies enabled");
        }

        // Handle Functional / Theme
        if (!settings.functional) {
            // If functional cookies are disabled, we should not persist the theme.
            // Since next-themes persists automatically to localStorage 'theme', we remove it.
            // This resets the user to system/default styling on next reload.
            localStorage.removeItem("theme");
            setTheme("light");
            console.log("Functional cookies disabled: Theme preference cleared.");
        }
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 z-[5000] flex items-end sm:items-center justify-center p-0 sm:p-4 bg-black/60 backdrop-blur-md transition-opacity duration-300">
            <div className="bg-[var(--card-bg)] border border-[var(--border-color)] shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto flex flex-col animate-in fade-in slide-in-from-bottom-4 duration-300 text-[var(--text-color)] sm:rounded-sm">

                {/* Header */}
                <div className="p-6 sm:p-8 border-b border-[var(--border-color)] flex justify-between items-start bg-[var(--card1-bg)]">
                    <div>
                        <h2 className="text-xl sm:text-2xl font-bold font-['Montserrat'] uppercase tracking-wide">
                            Nordic Storium
                        </h2>
                        <p className="text-sm font-medium text-[var(--accent-color)] mt-1">
                            {showPreferences ? "Inställningar för data & integritet" : "Vi värnar om din data"}
                        </p>
                    </div>
                    {showPreferences && (
                        <button onClick={() => setIsOpen(false)} className="text-[var(--text-secondary)] hover:text-red-600 transition-colors p-1">
                            <X size={24} />
                        </button>
                    )}
                </div>

                {/* Content */}
                <div className="p-6 sm:p-8 overflow-y-auto custom-scrollbar bg-[var(--background)]">
                    {!showPreferences ? (
                        <div className="space-y-6">
                            <div className="space-y-4 text-[var(--text-secondary)] leading-relaxed text-sm sm:text-base">
                                <p>
                                    <strong>Din integritet är viktig för oss.</strong> När du besöker Nordic Storium använder vi cookies och liknande tekniker för att säkerställa att webbplatsen fungerar korrekt (nödvändiga), för att spara dina preferenser (funktionella) och för att förstå hur våra besökare interagerar med sidan (analys).
                                </p>
                                <p>
                                    Vi värdesätter transparens. Genom att klicka på &quot;Godkänn alla&quot; samtycker du till användningen av alla cookies. Du kan när som helst ändra dina val eller återkalla ditt samtycke under &quot;Anpassa&quot; eller via länken i sidfoten.
                                </p>
                                <p className="text-xs sm:text-sm border-t border-[var(--border-color)] pt-4 mt-4">
                                    Personuppgiftsansvarig: <strong>Nordic Storium</strong> (Org.nr 559287-3612). <br />
                                    Läs mer om dina rättigheter i vår <Link href="/integritetspolicy" className="text-blue-600 hover:underline font-medium">Integritetspolicy</Link> och <Link href="/villkor" className="text-blue-600 hover:underline font-medium">Köpvillkor</Link>.
                                </p>
                            </div>
                        </div>
                    ) : (
                        <div className="space-y-8">
                            <p className="text-[var(--text-secondary)] text-sm sm:text-base">
                                Bestäm själv vilka data vi får samla in. Dina val sparas i 12 månader.
                            </p>

                            {/* Strictly Necessary */}
                            <div className="flex items-start justify-between gap-4 p-4 sm:p-5 bg-[var(--card-bg)] border border-[var(--border-color)]">
                                <div>
                                    <h3 className="font-bold text-sm sm:text-base uppercase tracking-wider text-[var(--text-heading)]">Nödvändiga</h3>
                                    <p className="text-xs sm:text-sm text-[var(--text-secondary)] mt-2 leading-relaxed">
                                        Dessa cookies är avgörande för webbplatsens säkerhet och grundläggande funktioner, såsom inloggning och navigering. De kan inte stängas av.
                                    </p>
                                </div>
                                <div className="relative inline-flex items-center cursor-not-allowed opacity-60">
                                    <div className="w-11 h-6 bg-blue-700 rounded-full peer-focus:outline-none ring-offset-2 peer-focus:ring-2 peer-focus:ring-blue-600 relative after:content-[''] after:absolute after:top-[2px] after:left-[22px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all"></div>
                                </div>
                            </div>

                            {/* Functional */}
                            <div className="flex items-start justify-between gap-4 p-4 sm:p-5 bg-[var(--card-bg)] border border-[var(--border-color)]">
                                <div>
                                    <h3 className="font-bold text-sm sm:text-base uppercase tracking-wider text-[var(--text-heading)]">Funktionella</h3>
                                    <p className="text-xs sm:text-sm text-[var(--text-secondary)] mt-2 leading-relaxed">
                                        Möjliggör funktioner som förbättrar din upplevelse, till exempel att spara ditt val av mörkt/ljust tema eller språkinställningar.
                                    </p>
                                </div>
                                <label className="relative inline-flex items-center cursor-pointer">
                                    <input
                                        type="checkbox"
                                        className="sr-only peer"
                                        checked={consent.functional}
                                        onChange={(e) => setConsent({ ...consent, functional: e.target.checked })}
                                    />
                                    <div className="w-11 h-6 bg-gray-300 peer-focus:outline-none rounded-full ring-offset-2 peer-focus:ring-2 peer-focus:ring-blue-600 dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                                </label>
                            </div>

                            {/* Analytics */}
                            <div className="flex items-start justify-between gap-4 p-4 sm:p-5 bg-[var(--card-bg)] border border-[var(--border-color)]">
                                <div>
                                    <h3 className="font-bold text-sm sm:text-base uppercase tracking-wider text-[var(--text-heading)]">Analys & Statistik</h3>
                                    <p className="text-xs sm:text-sm text-[var(--text-secondary)] mt-2 leading-relaxed">
                                        Hjälper oss att förstå hur besökare använder webbplatsen genom anonymiserad statistik, så att vi kan förbättra prestanda och innehåll.
                                    </p>
                                </div>
                                <label className="relative inline-flex items-center cursor-pointer">
                                    <input
                                        type="checkbox"
                                        className="sr-only peer"
                                        checked={consent.analytics}
                                        onChange={(e) => setConsent({ ...consent, analytics: e.target.checked })}
                                    />
                                    <div className="w-11 h-6 bg-gray-300 peer-focus:outline-none rounded-full ring-offset-2 peer-focus:ring-2 peer-focus:ring-blue-600 dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                                </label>
                            </div>

                        </div>
                    )}
                </div>

                {/* Footer Actions */}
                <div className="p-6 sm:p-8 border-t border-[var(--border-color)] bg-[var(--card1-bg)] flex flex-col sm:flex-row gap-4 justify-end sm:rounded-b-sm">
                    {!showPreferences ? (
                        <>
                            <button
                                onClick={() => setShowPreferences(true)}
                                className="px-6 py-3 text-sm font-bold uppercase tracking-wider text-[var(--text-color)] border-2 border-[var(--border-color)] hover:bg-[var(--background)] transition-colors"
                            >
                                Anpassa
                            </button>
                            <button
                                onClick={handleAcceptAll}
                                className="px-8 py-3 text-sm font-bold uppercase tracking-wider text-white bg-blue-600 hover:bg-blue-700 shadow-lg transition-all transform hover:-translate-y-0.5"
                            >
                                Godkänn alla
                            </button>
                        </>
                    ) : (
                        <>
                            <button
                                onClick={() => setShowPreferences(false)}
                                className="px-6 py-3 text-sm font-bold uppercase tracking-wider text-[var(--text-secondary)] hover:text-[var(--text-color)] transition-colors"
                            >
                                Tillbaka
                            </button>
                            <button
                                onClick={handleSavePreferences}
                                className="px-8 py-3 text-sm font-bold uppercase tracking-wider text-white bg-blue-600 hover:bg-blue-700 shadow-lg transition-all transform hover:-translate-y-0.5"
                            >
                                Spara mina val
                            </button>
                        </>
                    )}
                </div>

            </div>
        </div>
    );
}
