import React, { useMemo, useState } from 'react';
import {
  Box,
  Heading,
  Text,
  VStack,
  HStack,
  Switch,
  FormControl,
  FormLabel,
  Input,
  Button,
  useToast,
  Alert,
  AlertIcon,
  Card,
  CardBody,
} from '@chakra-ui/react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getPreferences, savePreferences, unsubscribeToken, SubscriberPreferences } from '../services/public/newsletter';
import { usePublicSettings } from '../hooks/usePublicSettings';
import { facrApi } from '../services/facr/facrApi';
import { trackEvent } from '../utils/umami';

const NewsletterPreferencesPage: React.FC = () => {
  const [params] = useSearchParams();
  const token = params.get('token') || '';
  const toast = useToast();
  const navigate = useNavigate();
  const qc = useQueryClient();

  const { data, isLoading, isError } = useQuery({
    queryKey: ['newsletter', 'prefs', token],
    queryFn: () => getPreferences(token),
    enabled: !!token,
  });

  // Load club competitions for nicer multi-select
  const { data: settings } = usePublicSettings();
  const clubId = settings?.club_id;
  const clubType = (settings?.club_type as 'football'|'futsal') || 'football';
  const { data: competitions } = useQuery({
    queryKey: ['facr', 'competitions', clubId, clubType],
    queryFn: async () => {
      if (!clubId) return [] as Array<{ code?: string; name?: string }>;
      const comps = await facrApi.getClubCompetitions(clubId, clubType);
      return comps || [];
    },
    enabled: !!clubId,
  });

  const initialPrefs: SubscriberPreferences = useMemo(() => ({
    blogs: true,
    matches: true,
    events: true,
    scores: false,
    ...(data?.preferences || {} as SubscriberPreferences),
  }), [data]);

  const [prefs, setPrefs] = useState<SubscriberPreferences>(initialPrefs);
  React.useEffect(() => { setPrefs(initialPrefs); }, [initialPrefs]);

  const saveMut = useMutation({
    mutationFn: () => savePreferences(token, prefs),
    onSuccess: () => {
      toast({ title: 'Preference uloženy', status: 'success' });
      qc.invalidateQueries({ queryKey: ['newsletter', 'prefs', token] });
      
      // Track preference save
      trackEvent('Newsletter Preferences Saved', {
        blogs: prefs.blogs,
        matches: prefs.matches,
        events: prefs.events,
        scores: prefs.scores,
      });
    },
    onError: (err: any) => toast({ title: 'Chyba při ukládání', description: String(err?.response?.data?.error || err?.message || err), status: 'error' }),
  });

  const unsubMut = useMutation({
    mutationFn: () => unsubscribeToken(token),
    onSuccess: () => {
      toast({ title: 'Odběr byl zrušen', status: 'success' });
      qc.invalidateQueries({ queryKey: ['newsletter', 'prefs', token] });
      
      // Track unsubscribe via preferences page
      trackEvent('Newsletter Unsubscribe', {
        success: true,
        source: 'preferences_page'
      });
      
      // Optionally redirect to home after a short delay
      setTimeout(() => navigate('/'), 1500);
    },
    onError: (err: any) => toast({ title: 'Chyba při odhlášení', description: String(err?.response?.data?.error || err?.message || err), status: 'error' }),
  });

  // helpers to handle competitions selection as comma-separated codes
  const selectedCodes = useMemo(() => {
    const raw = (prefs.competitions as string) || '';
    return new Set(raw.split(',').map((s) => s.trim()).filter(Boolean));
  }, [prefs.competitions]);
  const toggleCode = (code: string, on: boolean) => {
    const next = new Set(selectedCodes);
    if (on) next.add(code); else next.delete(code);
    const value = Array.from(next).join(', ');
    setPrefs({ ...prefs, competitions: value });
  };

  if (!token) {
    return (
      <Box maxW="640px" mx="auto" p={6}>
        <Alert status="error" borderRadius="md"><AlertIcon />Chybí parametr token v adrese.</Alert>
      </Box>
    );
  }

  if (isLoading) {
    return <Box maxW="640px" mx="auto" p={6}><Text>Načítání…</Text></Box>;
  }

  if (isError || !data) {
    return (
      <Box maxW="640px" mx="auto" p={6}>
        <Alert status="error" borderRadius="md"><AlertIcon />Neplatný nebo expirovaný token.</Alert>
      </Box>
    );
  }


  return (
    <Box maxW="720px" mx="auto" p={6}>
      <Heading size="lg" mb={2}>Nastavení newsletteru</Heading>
      <Text color="gray.600" mb={6}>Spravujte, jaké e-maily chcete dostávat na adresu {data.email}.</Text>

      <Card mb={6}><CardBody>
        <VStack spacing={4} align="stretch">
          <FormControl display="flex" alignItems="center" justifyContent="space-between">
            <FormLabel m={0}>Články (blog)</FormLabel>
            <Switch isChecked={!!prefs.blogs} onChange={(e) => setPrefs({ ...prefs, blogs: e.target.checked })} />
          </FormControl>
          <FormControl display="flex" alignItems="center" justifyContent="space-between">
            <FormLabel m={0}>Nadcházející zápasy</FormLabel>
            <Switch isChecked={!!prefs.matches} onChange={(e) => setPrefs({ ...prefs, matches: e.target.checked })} />
          </FormControl>
          <FormControl display="flex" alignItems="center" justifyContent="space-between">
            <FormLabel m={0}>Události</FormLabel>
            <Switch isChecked={!!prefs.events} onChange={(e) => setPrefs({ ...prefs, events: e.target.checked })} />
          </FormControl>
          <FormControl display="flex" alignItems="center" justifyContent="space-between">
            <FormLabel m={0}>Výsledky (souhrn týdne)</FormLabel>
            <Switch isChecked={!!prefs.scores} onChange={(e) => setPrefs({ ...prefs, scores: e.target.checked })} />
          </FormControl>
          <FormControl>
            <FormLabel>Preferované soutěže</FormLabel>
            {Array.isArray(competitions) && competitions.length > 0 ? (
              <VStack align="stretch" spacing={1} maxH="220px" overflowY="auto" borderWidth="1px" borderRadius="md" p={3}>
                {competitions.map((c: any, idx: number) => {
                  const code = (c?.code || c?.id || c?.name || `comp-${idx}`) as string;
                  const name = (c?.name || c?.code || code) as string;
                  const checked = selectedCodes.has(String(code));
                  return (
                    <HStack key={code} justify="space-between">
                      <Text>{name}</Text>
                      <Switch isChecked={checked} onChange={(e) => toggleCode(String(code), e.target.checked)} />
                    </HStack>
                  );
                })}
              </VStack>
            ) : (
              <Input placeholder="např. 5LM, POH" value={(prefs.competitions as string) || ''} onChange={(e) => setPrefs({ ...prefs, competitions: e.target.value })} />
            )}
            <Text mt={2} fontSize="sm" color="gray.500">Pokud není seznam k dispozici, můžete zadat kódy soutěží ručně, oddělené čárkou.</Text>
          </FormControl>
        </VStack>
      </CardBody></Card>

      <HStack spacing={3}>
        <Button 
          colorScheme="blue" 
          onClick={() => saveMut.mutate()} 
          isLoading={saveMut.isLoading}
          data-umami-event="Save Preferences"
        >
          Uložit
        </Button>
        <Button 
          variant="outline" 
          onClick={() => qc.invalidateQueries({ queryKey: ['newsletter', 'prefs', token] })}
          data-umami-event="Refresh Preferences"
        >
          Obnovit
        </Button>
        <Button 
          colorScheme="red" 
          variant="outline" 
          onClick={() => unsubMut.mutate()} 
          isLoading={unsubMut.isLoading}
          data-umami-event="Unsubscribe"
          data-umami-event-source="preferences"
        >
          Zrušit odběr
        </Button>
      </HStack>
    </Box>
  );
};

export default NewsletterPreferencesPage;
