import { useEffect, useState } from "react";

export interface CookiePreferences {
  essential: boolean;
  analytics: boolean;
  marketing: boolean;
}

const COOKIE_CONSENT_KEY = "xtablo-cookie-consent";
const COOKIE_CONSENT_VERSION = "2"; // Increment this when you need users to re-consent

interface StoredConsent {
  preferences: CookiePreferences;
  timestamp: number;
  version: string;
}

export const useCookieConsent = () => {
  const [hasConsent, setHasConsent] = useState<boolean | null>(null);
  const [showBanner, setShowBanner] = useState(false);
  const [preferences, setPreferences] = useState<CookiePreferences>({
    essential: true,
    analytics: false,
    marketing: false,
  });

  useEffect(() => {
    const storedConsent = localStorage.getItem(COOKIE_CONSENT_KEY);

    if (storedConsent) {
      try {
        const parsed: StoredConsent = JSON.parse(storedConsent);

        // Check if the consent is for the current version
        if (parsed.version === COOKIE_CONSENT_VERSION) {
          setPreferences(parsed.preferences);
          setHasConsent(true);
          setShowBanner(false);
        } else {
          // Version mismatch, show banner again
          setHasConsent(false);
          setShowBanner(true);
        }
      } catch (error) {
        console.error("Failed to parse cookie consent:", error);
        setHasConsent(false);
        setShowBanner(true);
      }
    } else {
      setHasConsent(false);
      setShowBanner(true);
    }
  }, []);

  const saveConsent = (newPreferences: CookiePreferences) => {
    const consent: StoredConsent = {
      preferences: newPreferences,
      timestamp: Date.now(),
      version: COOKIE_CONSENT_VERSION,
    };

    localStorage.setItem(COOKIE_CONSENT_KEY, JSON.stringify(consent));
    setPreferences(newPreferences);
    setHasConsent(true);
    setShowBanner(false);

    // Reload the page to apply new consent settings
    window.location.reload();
  };

  const acceptAll = () => {
    saveConsent({
      essential: true,
      analytics: true,
      marketing: true,
    });
  };

  const rejectAll = () => {
    saveConsent({
      essential: true,
      analytics: false,
      marketing: false,
    });
  };

  const resetConsent = () => {
    localStorage.removeItem(COOKIE_CONSENT_KEY);
    setHasConsent(false);
    setShowBanner(true);
    setPreferences({
      essential: true,
      analytics: false,
      marketing: false,
    });
  };

  const openPreferences = () => {
    setShowBanner(true);
  };

  return {
    hasConsent,
    showBanner,
    preferences,
    acceptAll,
    rejectAll,
    saveConsent,
    resetConsent,
    openPreferences,
    hidesBanner: () => setShowBanner(false),
  };
};

export const getCookieConsent = (): CookiePreferences | null => {
  if (typeof window === "undefined") return null;

  const storedConsent = localStorage.getItem(COOKIE_CONSENT_KEY);

  if (!storedConsent) return null;

  try {
    const parsed: StoredConsent = JSON.parse(storedConsent);

    // Check if the consent is for the current version
    if (parsed.version === COOKIE_CONSENT_VERSION) {
      return parsed.preferences;
    }

    return null;
  } catch (error) {
    console.error("Failed to parse cookie consent:", error);
    return null;
  }
};
