'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';

const STORAGE_KEY = 'cookie-consent-v1';

type ConsentValue = {
  necessary: true;
  comfort: boolean;
  statistics: boolean;
  marketing: boolean;
  decidedAt: string;
};

const DEFAULT_CONSENT: ConsentValue = {
  necessary: true,
  comfort: false,
  statistics: false,
  marketing: false,
  decidedAt: '',
};

function readConsent(): ConsentValue | null {
  if (typeof window === 'undefined') return null;
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return null;
    return JSON.parse(raw) as ConsentValue;
  } catch {
    return null;
  }
}

function writeConsent(consent: ConsentValue) {
  if (typeof window === 'undefined') return;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(consent));
  window.dispatchEvent(new CustomEvent('cookie-consent-updated', { detail: consent }));
}

export default function CookieConsent() {
  const [visible, setVisible] = useState(false);
  const [showConfigure, setShowConfigure] = useState(false);
  const [prefs, setPrefs] = useState<ConsentValue>(DEFAULT_CONSENT);

  // Settings → Basic information → Security and Privacy. `useDefaultConsent`
  // controls whether this default banner is rendered at all; `acceptAll`
  // controls whether the "Accept all" button is offered.
  const [useDefaultConsent, setUseDefaultConsent] = useState(true);
  const [acceptAll, setAcceptAll] = useState(false);

  useEffect(() => {
    const existing = readConsent();
    if (!existing) setVisible(true);
    else setPrefs(existing);

    fetch('/api/storefront-settings', { cache: 'no-store' })
      .then((res) => res.json())
      .then((s) => {
        setUseDefaultConsent(s.useDefaultCookieConsent !== false);
        setAcceptAll(Boolean(s.acceptAllCookies));
      })
      .catch(() => {});
  }, []);

  // Admin disabled the default cookie notification — render nothing.
  if (!useDefaultConsent) return null;
  if (!visible) return null;

  const saveAll = () => {
    const v: ConsentValue = {
      necessary: true,
      comfort: true,
      statistics: true,
      marketing: true,
      decidedAt: new Date().toISOString(),
    };
    writeConsent(v);
    setVisible(false);
  };

  const saveOnlyNecessary = () => {
    const v: ConsentValue = {
      ...DEFAULT_CONSENT,
      decidedAt: new Date().toISOString(),
    };
    writeConsent(v);
    setVisible(false);
  };

  const saveSelected = () => {
    const v: ConsentValue = {
      ...prefs,
      necessary: true,
      decidedAt: new Date().toISOString(),
    };
    writeConsent(v);
    setVisible(false);
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="cookie-consent-title"
      className="fixed inset-x-0 bottom-0 z-[60] p-4 sm:p-6"
    >
      <div className="max-w-3xl mx-auto bg-white border border-surface-200 rounded-2xl shadow-2xl overflow-hidden">
        <div className="px-6 py-5">
          <h2 id="cookie-consent-title" className="text-lg font-bold text-surface-900 mb-2">
            We value your privacy
          </h2>
          <p className="text-sm text-surface-600">
            We use cookies and similar technologies to give you the best experience, analyse usage,
            and personalise content. You can accept all or configure your preferences. See our{' '}
            <Link href="/privacy" className="text-brand-600 hover:underline">
              privacy policy
            </Link>{' '}
            for details.
          </p>

          {showConfigure && (
            <div className="mt-4 space-y-3 border-t border-surface-100 pt-4">
              <Row label="Necessary" description="Required for the site to function." disabled checked />
              <Row
                label="Comfort"
                description="Remembers preferences (language, currency, recently viewed)."
                checked={prefs.comfort}
                onChange={(v) => setPrefs((p) => ({ ...p, comfort: v }))}
              />
              <Row
                label="Statistics"
                description="Anonymous analytics to improve the shop."
                checked={prefs.statistics}
                onChange={(v) => setPrefs((p) => ({ ...p, statistics: v }))}
              />
              <Row
                label="Marketing"
                description="Personalised ads and offers."
                checked={prefs.marketing}
                onChange={(v) => setPrefs((p) => ({ ...p, marketing: v }))}
              />
            </div>
          )}

          <div className="mt-5 flex flex-col sm:flex-row gap-2 sm:gap-3">
            {!showConfigure ? (
              <>
                {acceptAll && (
                  <button
                    type="button"
                    onClick={saveAll}
                    className="flex-1 px-5 py-2.5 bg-brand-500 hover:bg-brand-600 text-white text-sm font-semibold rounded-lg transition-colors"
                  >
                    Accept all
                  </button>
                )}
                <button
                  type="button"
                  onClick={() => setShowConfigure(true)}
                  className={`flex-1 px-5 py-2.5 text-sm font-semibold rounded-lg transition-colors ${
                    acceptAll
                      ? 'border border-surface-300 hover:border-surface-400 text-surface-700'
                      : 'bg-brand-500 hover:bg-brand-600 text-white'
                  }`}
                >
                  Configure
                </button>
                <button
                  type="button"
                  onClick={saveOnlyNecessary}
                  className="px-5 py-2.5 text-surface-500 hover:text-surface-700 text-sm font-medium transition-colors"
                >
                  Reject all
                </button>
              </>
            ) : (
              <>
                <button
                  type="button"
                  onClick={saveSelected}
                  className="flex-1 px-5 py-2.5 bg-brand-500 hover:bg-brand-600 text-white text-sm font-semibold rounded-lg transition-colors"
                >
                  Save selection
                </button>
                {acceptAll && (
                  <button
                    type="button"
                    onClick={saveAll}
                    className="flex-1 px-5 py-2.5 border border-surface-300 hover:border-surface-400 text-surface-700 text-sm font-semibold rounded-lg transition-colors"
                  >
                    Accept all
                  </button>
                )}
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function Row({
  label,
  description,
  checked,
  disabled,
  onChange,
}: {
  label: string;
  description: string;
  checked: boolean;
  disabled?: boolean;
  onChange?: (v: boolean) => void;
}) {
  return (
    <label className={`flex items-start gap-3 ${disabled ? 'opacity-70' : 'cursor-pointer'}`}>
      <input
        type="checkbox"
        className="mt-1 w-4 h-4 rounded border-surface-300 text-brand-500 focus:ring-brand-400 disabled:opacity-100"
        checked={checked}
        disabled={disabled}
        onChange={(e) => onChange?.(e.target.checked)}
      />
      <div className="text-sm">
        <p className="font-medium text-surface-900">{label}</p>
        <p className="text-surface-500 text-xs">{description}</p>
      </div>
    </label>
  );
}
