import { ChevronDown, ChevronUp } from 'lucide-react';

import { useCallback, useEffect, useState } from 'react';

import { Button } from '@/Components/ui/button';
import { Switch } from '@/Components/ui/switch';
import { loadAnalytics, trackConsentDecision, trackProductEvent } from '@/lib/analytics';
import {
  CATEGORIES_COOKIE_NAME,
  CONSENT_COOKIE_NAME,
  type ConsentCategories,
  getConsentStatus,
  resetAnalyticsIdentity,
  setCookieConsent,
} from '@/lib/cookieConsent';
import { CONSENT_DECISION } from '@/lib/event-catalog';

function setConsentCookie(status: 'accepted' | 'declined'): void {
  setCookieConsent(CONSENT_COOKIE_NAME, status);
}

function setCategoriesCookie(categories: ConsentCategories): void {
  setCookieConsent(CATEGORIES_COOKIE_NAME, JSON.stringify(categories));
}

async function postConsent(categories: ConsentCategories): Promise<void> {
  try {
    const csrfToken = (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)
      ?.content;
    await fetch('/cookie-consent', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
        ...(csrfToken ? { 'X-CSRF-TOKEN': csrfToken } : {}),
      },
      body: JSON.stringify({ categories }),
    });
  } catch {
    // noop — server-side consent is best-effort; browser cookie is the primary UX signal
  }
}

export default function CookieConsentBanner() {
  const [visible, setVisible] = useState(false);
  const [customizing, setCustomizing] = useState(false);
  const [analytics, setAnalytics] = useState(false);
  const [marketing, setMarketing] = useState(false);

  useEffect(() => {
    if (getConsentStatus() === null) {
      setVisible(true);
    }
  }, []);

  const buildCategories = useCallback(
    (analyticsOn: boolean, marketingOn: boolean): ConsentCategories => ({
      necessary: true,
      analytics: analyticsOn,
      marketing: marketingOn,
    }),
    [],
  );

  const updateGtagConsent = useCallback((analyticsGranted: boolean) => {
    if (typeof window !== 'undefined' && typeof window.gtag === 'function') {
      window.gtag('consent', 'update', {
        analytics_storage: analyticsGranted ? 'granted' : 'denied',
      });
    }
    trackProductEvent(CONSENT_DECISION, { analytics: analyticsGranted });
  }, []);

  const handleAccept = useCallback(async () => {
    const categories = buildCategories(true, true);
    setConsentCookie('accepted');
    setCategoriesCookie(categories);
    setVisible(false);
    updateGtagConsent(true);
    // Initialize PostHog immediately now that analytics consent has been granted in this session.
    loadAnalytics();
    // Fire server-side regardless of consent state so we can measure acceptance rate.
    trackConsentDecision(true, true, 'accept_all');
    await postConsent(categories);
  }, [buildCategories, updateGtagConsent]);

  const handleDecline = useCallback(async () => {
    const categories = buildCategories(false, false);
    setConsentCookie('declined');
    setCategoriesCookie(categories);
    setVisible(false);
    updateGtagConsent(false);
    resetAnalyticsIdentity();
    // Fire server-side regardless of consent state so we can measure acceptance rate.
    trackConsentDecision(false, false, 'decline_all');
    await postConsent(categories);
  }, [buildCategories, updateGtagConsent]);

  const handleSavePreferences = useCallback(async () => {
    const categories = buildCategories(analytics, marketing);
    const status = analytics || marketing ? 'accepted' : 'declined';
    setConsentCookie(status);
    setCategoriesCookie(categories);
    setVisible(false);
    updateGtagConsent(analytics);
    if (analytics) {
      // Initialize PostHog immediately when analytics consent is granted in this session.
      loadAnalytics();
    } else {
      resetAnalyticsIdentity();
    }
    // Fire server-side regardless of consent state so we can measure acceptance rate.
    trackConsentDecision(analytics, marketing, 'custom');
    await postConsent(categories);
  }, [analytics, marketing, buildCategories, updateGtagConsent]);

  if (!visible) return null;

  return (
    <div
      role="dialog"
      aria-label="Cookie consent"
      className="fixed bottom-0 left-0 right-0 z-50 border-t bg-background shadow-lg"
    >
      <div className="container mx-auto max-w-5xl p-4 sm:p-6">
        {/* Main row */}
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <p className="max-w-2xl text-sm text-muted-foreground">
            We use cookies to improve your experience and analyze site usage. You can accept all
            cookies, decline non-essential ones, or customize your preferences.{' '}
            <a href="/privacy" className="underline hover:text-foreground">
              Privacy Policy
            </a>
          </p>
          <div className="flex shrink-0 flex-wrap gap-2">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setCustomizing((c) => !c)}
              aria-expanded={customizing}
              aria-controls="cookie-customize-panel"
              className="text-muted-foreground"
            >
              Customize
              {customizing ? (
                <ChevronUp className="ml-1 h-3 w-3" />
              ) : (
                <ChevronDown className="ml-1 h-3 w-3" />
              )}
            </Button>
            <Button variant="outline" size="sm" onClick={handleDecline}>
              Decline
            </Button>
            <Button size="sm" onClick={handleAccept}>
              Accept all
            </Button>
          </div>
        </div>

        {/* Granular preferences panel */}
        {customizing && (
          <div id="cookie-customize-panel" className="mt-4 space-y-3 border-t pt-4">
            <p className="text-xs font-medium text-foreground">Cookie preferences</p>
            <div className="flex flex-col gap-3 sm:flex-row sm:gap-6">
              {/* Necessary — always on */}
              <div className="flex items-center gap-3">
                <Switch checked disabled aria-label="Necessary cookies" />
                <div>
                  <p className="text-sm font-medium">Necessary</p>
                  <p className="text-xs text-muted-foreground">Required for the service to work</p>
                </div>
              </div>

              {/* Analytics */}
              <div className="flex items-center gap-3">
                <Switch
                  checked={analytics}
                  onCheckedChange={setAnalytics}
                  aria-label="Analytics cookies"
                />
                <div>
                  <p className="text-sm font-medium">Analytics</p>
                  <p className="text-xs text-muted-foreground">
                    Help us understand how you use the app
                  </p>
                </div>
              </div>

              {/* Marketing — no marketing cookies are currently in use */}
              <div className="flex items-center gap-3">
                <Switch
                  checked={marketing}
                  onCheckedChange={setMarketing}
                  aria-label="Marketing cookies"
                />
                <div>
                  <p className="text-sm font-medium">Marketing</p>
                  <p className="text-xs text-muted-foreground">
                    Not currently in use. Reserved for future marketing integrations.
                  </p>
                </div>
              </div>
            </div>

            <Button size="sm" onClick={handleSavePreferences} className="mt-2">
              Save preferences
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}
