import { Box, Button, Flex, Text, Link } from '@chakra-ui/react';
import { useEffect, useState } from 'react';

const STORAGE_KEY = 'cookie_consent';

type Consent = {
  version: number;
  necessary: true; // always true
  preferences: boolean;
  analytics: boolean;
  marketing: boolean;
  timestamp: string; // ISO
};

const defaultConsent: Consent = {
  version: 1,
  necessary: true,
  preferences: false,
  analytics: false,
  marketing: false,
  timestamp: new Date().toISOString(),
};

const CookieBanner: React.FC = () => {
  const [visible, setVisible] = useState(false);
  const [managing, setManaging] = useState(false);
  const [consent, setConsent] = useState<Consent>(defaultConsent);

  useEffect(() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved) {
        const parsed = JSON.parse(saved) as Consent;
        setConsent(parsed);
        setVisible(false);
      } else {
        setVisible(true);
      }
    } catch {
      setVisible(true);
    }
  }, []);

  const saveAndClose = (c: Consent) => {
    const payload = { ...c, timestamp: new Date().toISOString() };
    localStorage.setItem(STORAGE_KEY, JSON.stringify(payload));
    setConsent(payload);
    setVisible(false);
    setManaging(false);
    // Dispatch a small custom event so analytics loaders can react
    window.dispatchEvent(new CustomEvent('cookie-consent-change', { detail: payload }));
  };

  const acceptAll = () => {
    saveAndClose({ ...defaultConsent, preferences: true, analytics: true, marketing: true });
  };

  const rejectNonEssential = () => {
    saveAndClose({ ...defaultConsent });
  };

  if (!visible) return null;

  return (
    <Box role="dialog" aria-live="polite" position="fixed" bottom={0} left={0} right={0} bg="gray.900" color="gray.100" zIndex={1000} py={4} px={4}>
      <Flex align="start" justify="space-between" gap={6} wrap="wrap">
        <Box maxW={{ base: '100%', md: '70%' }}>
          <Text fontSize="sm" mb={2}>
            Tento web používá soubory cookies pro zajištění správného fungování (nezbytné) a za účelem vylepšení obsahu. 
            O vybraných kategoriích rozhodujete vy. Podrobnosti najdete v&nbsp;
            <Link href="/pravidla-cookies" color="blue.300" textDecoration="underline">Pravidlech cookies</Link>.
          </Text>
          {managing && (
            <Box mt={3} bg="gray.800" borderRadius="md" p={3} border="1px solid" borderColor="gray.700">
              <Text fontWeight="semibold" mb={2}>Nastavení preferencí</Text>
              <Flex direction="column" gap={2}>
                <label style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <input type="checkbox" checked readOnly />
                  <Text fontSize="sm">Nezbytné cookies (vždy aktivní)</Text>
                </label>
                <label style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <input
                    type="checkbox"
                    checked={!!consent.preferences}
                    onChange={(e) => setConsent((c) => ({ ...c, preferences: e.target.checked }))}
                  />
                  <Text fontSize="sm">Preferenční cookies (např. zapamatování voleb)</Text>
                </label>
                <label style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <input
                    type="checkbox"
                    checked={!!consent.analytics}
                    onChange={(e) => setConsent((c) => ({ ...c, analytics: e.target.checked }))}
                  />
                  <Text fontSize="sm">Analytické cookies (anonymní měření návštěvnosti)</Text>
                </label>
                <label style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <input
                    type="checkbox"
                    checked={!!consent.marketing}
                    onChange={(e) => setConsent((c) => ({ ...c, marketing: e.target.checked }))}
                  />
                  <Text fontSize="sm">Marketingové cookies</Text>
                </label>
                <Flex gap={2} mt={2} wrap="wrap">
                  <Button size="sm" colorScheme="blue" onClick={() => saveAndClose(consent)}>Uložit nastavení</Button>
                  <Button size="sm" variant="outline" onClick={() => setManaging(false)}>Zpět</Button>
                </Flex>
              </Flex>
            </Box>
          )}
        </Box>
        <Flex gap={2} align="center" wrap="wrap">
          <Button size="sm" onClick={() => setManaging((v) => !v)} variant="outline">Nastavit</Button>
          <Button size="sm" onClick={rejectNonEssential} variant="ghost">Odmítnout nepovinné</Button>
          <Button size="sm" colorScheme="blue" onClick={acceptAll}>Přijmout vše</Button>
        </Flex>
      </Flex>
    </Box>
  );
};

export default CookieBanner;
