import React, { useEffect, useState } from 'react';
import {
  Box,
  Button,
  Flex,
  FormControl,
  FormLabel,
  FormHelperText,
  Heading,
  IconButton,
  Table,
  Tbody,
  Td,
  Text,
  Th,
  Thead,
  Tr,
  useDisclosure,
  useToast,
  Badge,
  Input,
  InputGroup,
  InputLeftElement,
  HStack,
  VStack,
  Textarea,
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalBody,
  ModalCloseButton,
  useBreakpointValue,
  Switch,
  Tooltip,
  Spinner,
  InputRightElement,
  Checkbox,
  Select,
  Tabs,
  TabList,
  Tab,
  TabPanels,
  TabPanel,
  useColorModeValue,
} from '@chakra-ui/react';
import { AddIcon, DeleteIcon, EmailIcon, SearchIcon } from '@chakra-ui/icons';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { format } from 'date-fns';
import { cs } from 'date-fns/locale';
import AdminLayout from '../../layouts/AdminLayout';
import {
  getNewsletterSubscribers,
  sendNewsletter,
  sendNewsletterTest,
  deleteSubscriber,
  toggleSubscriberStatus,
  NewsletterSubscriber,
  NewsletterSendData,
  getNewsletterStatus,
  sendNewsletterTestAdvanced,
  NewsletterTestType,
  sendNewsletterDigest,
  setNewsletterAutomation,
  previewNewsletter,
  DigestType,
} from '../../services/admin/newsletter';
import { getAdminSettings, updateAdminSettings, AdminSettings } from '../../services/settings';
import { adminSendSmtpTest, AdminSmtpTestPayload } from '../../services/admin/newsletter';
import { getRecentEmailStats, EmailStatRow, getEmailEventsForLog, EmailEventRow } from '../../services/admin/newsletter';

export default function NewsletterAdminPage() {
  const cardBg = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.700');
  const inputBg = useColorModeValue('white', 'gray.700');
  const textSecondary = useColorModeValue('gray.600', 'gray.400');
  const hoverBg = useColorModeValue('gray.50', 'gray.700');
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedSubscribers, setSelectedSubscribers] = useState<number[]>([]);
  const [newsletterData, setNewsletterData] = useState<NewsletterSendData>({
    subject: '',
    content: '',
  });

  // SMTP test (admin)
  const [smtpHost, setSmtpHost] = useState('');
  const [smtpPort, setSmtpPort] = useState<number | ''>('');
  const [smtpUser, setSmtpUser] = useState('');
  const [smtpPass, setSmtpPass] = useState('');
  const [smtpFrom, setSmtpFrom] = useState('');
  const [smtpTo, setSmtpTo] = useState('');
  const [smtpTLS, setSmtpTLS] = useState(true);
  const [smtpSubject, setSmtpSubject] = useState('SMTP Test');
  const [smtpBody, setSmtpBody] = useState('<p>Toto je testovací e‑mail (admin SMTP debug).</p>');
  const [showSmtpPass, setShowSmtpPass] = useState(false);

  const adminSmtpTestMutation = useMutation({
    mutationFn: async () => {
      const payload: AdminSmtpTestPayload = {
        host: smtpHost.trim(),
        port: typeof smtpPort === 'number' ? smtpPort : 0,
        username: smtpUser || undefined,
        password: smtpPass || undefined,
        from: smtpFrom.trim(),
        to: smtpTo.trim(),
        subject: smtpSubject || undefined,
        body: smtpBody || undefined,
        use_tls: smtpTLS,
      };
      return adminSendSmtpTest(payload);
    },
    onSuccess: (res: any) => {
      if (res?.ok) {
        toast({ title: 'SMTP test úspěšný', description: res?.message || 'Test email sent', status: 'success' });
      } else {
        toast({ title: 'SMTP test selhal', description: res?.error || 'Chyba při odeslání testu', status: 'error' });
      }
    },
    onError: (err: any) => {
      toast({ title: 'Chyba požadavku', description: err?.response?.data?.error || err?.message, status: 'error' });
    }
  });
  const [testEmail, setTestEmail] = useState<string>('');
  const [testEmails, setTestEmails] = useState<string>('');
  const [testType, setTestType] = useState<NewsletterTestType>('newsletter');
  const [prefsModalOpen, setPrefsModalOpen] = useState(false);
  const [editingSubscriber, setEditingSubscriber] = useState<NewsletterSubscriber | null>(null);
  const [editingPrefs, setEditingPrefs] = useState<Record<string, boolean>>({});
  // Send mode: custom body or digest template
  const [sendMode, setSendMode] = useState<'custom' | DigestType>('custom');
  const [competitions, setCompetitions] = useState<string>('');
  const [previewSubject, setPreviewSubject] = useState<string>('');
  const [previewHtml, setPreviewHtml] = useState<string>('');
  const [previewLoading, setPreviewLoading] = useState<boolean>(false);
  
  
  const { isOpen, onOpen, onClose } = useDisclosure();
  const testModal = useDisclosure();
  const smtpModal = useDisclosure();
  const toast = useToast();
  const queryClient = useQueryClient();
  const isMobile = useBreakpointValue({ base: true, md: false });

  // Admin settings (for scheduling)
  const settingsQuery = useQuery({
    queryKey: ['admin', 'settings'],
    queryFn: getAdminSettings,
  });
  const settings = settingsQuery.data as AdminSettings | undefined;
  const [enableWeekly, setEnableWeekly] = useState<boolean>(!!settings?.enable_weekly);
  const [enableMatchReminders, setEnableMatchReminders] = useState<boolean>(!!settings?.enable_match_reminders);
  const [enableResults, setEnableResults] = useState<boolean>(!!settings?.enable_results);
  const [weeklyDay, setWeeklyDay] = useState<AdminSettings['newsletter_weekly_day']>(settings?.newsletter_weekly_day || 'sun');
  const [weeklyHour, setWeeklyHour] = useState<number>(typeof settings?.newsletter_weekly_hour === 'number' ? (settings!.newsletter_weekly_hour as number) : 18);
  const [reminderLead, setReminderLead] = useState<number>(typeof settings?.newsletter_reminder_lead_hours === 'number' ? (settings!.newsletter_reminder_lead_hours as number) : 48);
  const [quietStart, setQuietStart] = useState<number>(typeof settings?.newsletter_quiet_start === 'number' ? (settings!.newsletter_quiet_start as number) : 22);
  const [quietEnd, setQuietEnd] = useState<number>(typeof settings?.newsletter_quiet_end === 'number' ? (settings!.newsletter_quiet_end as number) : 7);

  // Sync local state when settings load
  useEffect(() => {
    if (!settings) return;
    setEnableWeekly(!!settings.enable_weekly);
    setEnableMatchReminders(!!settings.enable_match_reminders);
    setEnableResults(!!settings.enable_results);
    setWeeklyDay(settings.newsletter_weekly_day || 'sun');
    setWeeklyHour(typeof settings.newsletter_weekly_hour === 'number' ? settings.newsletter_weekly_hour! : 18);
    setReminderLead(typeof settings.newsletter_reminder_lead_hours === 'number' ? settings.newsletter_reminder_lead_hours! : 48);
    setQuietStart(typeof settings.newsletter_quiet_start === 'number' ? settings.newsletter_quiet_start! : 22);
    setQuietEnd(typeof settings.newsletter_quiet_end === 'number' ? settings.newsletter_quiet_end! : 7);
  }, [settings]);

  const saveScheduleMutation = useMutation({
    mutationFn: () => updateAdminSettings({
      enable_weekly: enableWeekly,
      enable_match_reminders: enableMatchReminders,
      enable_results: enableResults,
      newsletter_weekly_day: weeklyDay,
      newsletter_weekly_hour: weeklyHour,
      newsletter_reminder_lead_hours: reminderLead,
      newsletter_quiet_start: quietStart,
      newsletter_quiet_end: quietEnd,
    }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'settings'] });
      toast({ title: 'Nastavení rozesílek uloženo', status: 'success' });
    },
    onError: (err: any) => {
      toast({ title: 'Chyba při ukládání', description: err?.response?.data?.error || err?.message, status: 'error' });
    }
  });

  // Basic client-side sanitizer for preview (defense-in-depth; backend should still sanitize)
  const sanitizeHtml = (html: string): string => {
    try {
      // Remove script/style/iframe tags entirely
      const withoutDangerousTags = html.replace(/<\s*(script|style|iframe)[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi, '');
      // Remove event handlers like onClick, onError, etc.
      const withoutEvents = withoutDangerousTags.replace(/ on[a-zA-Z]+\s*=\s*"[^"]*"/g, '').replace(/ on[a-zA-Z]+\s*=\s*'[^']*'/g, '').replace(/ on[a-zA-Z]+\s*=\s*[^\s>]+/g, '');
      // Neutralize javascript:, data: URLs in href/src
      const neutralizedUrls = withoutEvents.replace(/(href|src)\s*=\s*(["'])\s*(javascript:|data:)/gi, '$1=$2#');
      return neutralizedUrls;
    } catch {
      return '';
    }
  };

  // Fetch subscribers
  const { data: subscribers = [], isLoading } = useQuery({
    queryKey: ['admin', 'newsletter-subscribers'],
    queryFn: getNewsletterSubscribers,
  });

  // Filter subscribers based on search term
  const filteredSubscribers = subscribers.filter((subscriber) =>
    subscriber.email.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // Toggle subscriber status
  const toggleStatusMutation = useMutation({
    mutationFn: ({ id, isActive }: { id: number; isActive: boolean }) =>
      toggleSubscriberStatus(id, isActive),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'newsletter-subscribers'] });
      toast({
        title: 'Stav odběratele byl aktualizován',
        status: 'success',
        duration: 3000,
        isClosable: true,
      });
    },
  });

  // Delete subscriber
  const deleteMutation = useMutation({
    mutationFn: deleteSubscriber,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'newsletter-subscribers'] });
      setSelectedSubscribers([]);
      toast({
        title: 'Odběratel byl smazán',
        status: 'success',
        duration: 3000,
        isClosable: true,
      });
    },
  });

  const updatePrefsMutation = useMutation({
    mutationFn: ({ id, prefs }: { id: number; prefs: Record<string, boolean> }) =>
      // lazy import to avoid cyclic imports
      import('../../services/admin/newsletter').then((m) => m.updateSubscriberPreferences(id, prefs)),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'newsletter-subscribers'] });
      setPrefsModalOpen(false);
      toast({ title: 'Preference uloženy', status: 'success' });
    },
    onError: (err: any) => {
      toast({ title: 'Chyba při ukládání preferencí', description: err?.response?.data?.error || err?.message, status: 'error' });
    },
  });

  // Send newsletter
  const sendNewsletterMutation = useMutation({
    mutationFn: sendNewsletter,
    onSuccess: () => {
      onClose();
      setNewsletterData({ subject: '', content: '' });
      toast({
        title: 'Newsletter byl odeslán',
        status: 'success',
        duration: 5000,
        isClosable: true,
      });
    },
    onError: (error: any) => {
      toast({
        title: 'Chyba při odesílání newsletteru',
        description: error?.response?.data?.error || error?.response?.data?.message || error?.message || 'Došlo k chybě',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    },
  });

  // Send test newsletter
  const sendTestMutation = useMutation({
    mutationFn: () => {
      const emails = testEmails
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean);
      if (emails.length > 0) {
        return sendNewsletterTestAdvanced({ emails, type: testType });
      }
      if (testEmail) {
        return sendNewsletterTestAdvanced({ email: testEmail, type: testType });
      }
      return sendNewsletterTestAdvanced({ type: testType });
    },
    onSuccess: (data: { message: string; recipient?: string; recipients?: string[]; type: string }) => {
      toast({
        title: 'Test odeslán',
        description:
          data?.recipients && data.recipients.length > 0
            ? `E-mail byl odeslán na ${data.recipients.join(', ')}`
            : data?.recipient
            ? `E-mail byl odeslán na ${data.recipient}`
            : 'Testovací e-mail byl odeslán',
        status: 'success',
        duration: 4000,
        isClosable: true,
      });
      setTestEmail('');
      setTestEmails('');
      testModal.onClose();
    },
    onError: (error: any) => {
      toast({
        title: 'Chyba při odesílání testu',
        description: error?.response?.data?.error || error?.response?.data?.message || error?.message || 'Došlo k chybě',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    },
  });

  const handleSelectAll = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.checked) {
      setSelectedSubscribers(filteredSubscribers.map((s) => s.id));
    } else {
      setSelectedSubscribers([]);
    }
  };

  const handleSelectSubscriber = (id: number, isSelected: boolean) => {
    if (isSelected) {
      setSelectedSubscribers((prev) => [...prev, id]);
    } else {
      setSelectedSubscribers((prev) => prev.filter((subId) => subId !== id));
    }
  };

  const handleDeleteSelected = () => {
    if (window.confirm('Opravdu chcete smazat vybrané odběratele?')) {
      Promise.all(selectedSubscribers.map((id) => deleteMutation.mutateAsync(id)));
    }
  };

  const handleSendNewsletter = () => {
    sendNewsletterMutation.mutate(newsletterData);
  };

  const formatDate = (dateString: string) => {
    return format(new Date(dateString), 'd. M. yyyy HH:mm', { locale: cs });
  };

  // Newsletter status
  const { data: statusData } = useQuery({
    queryKey: ['admin', 'newsletter-status'],
    queryFn: getNewsletterStatus,
  });
  const automationToggle = useMutation({
    mutationFn: (enabled: boolean) => setNewsletterAutomation(enabled),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['admin', 'newsletter-status'] }),
  });

  // Recent delivery stats
  const { data: recentStats = [], isLoading: statsLoading } = useQuery<EmailStatRow[]>({
    queryKey: ['admin', 'newsletter-stats-recent'],
    queryFn: getRecentEmailStats,
  });

  // Events modal state
  const [eventsModalOpen, setEventsModalOpen] = useState(false);
  const [activeLog, setActiveLog] = useState<EmailStatRow | null>(null);
  const eventsQuery = useQuery<EmailEventRow[]>({
    queryKey: ['admin', 'email-events', activeLog?.id],
    queryFn: () => getEmailEventsForLog(activeLog?.id || 0),
    enabled: !!activeLog?.id && eventsModalOpen,
  });
  const [eventFilter, setEventFilter] = useState<{ open: boolean; click: boolean; spam: boolean; unsubscribe: boolean }>({ open: true, click: true, spam: true, unsubscribe: true });
  const filteredEvents = (eventsQuery.data || []).filter((ev) => eventFilter[(ev.event_type as 'open'|'click'|'spam'|'unsubscribe')] ?? true);

  const exportCSV = () => {
    // Prevent CSV injection by prefixing dangerous leading characters
    const safeCSV = (value: any) => {
      const s = String(value ?? '');
      return /^[=+\-@]/.test(s) ? `'${s}` : s;
    };
    const rows = (eventsQuery.data || []).map((ev) => ({
      id: ev.id,
      created_at: ev.created_at,
      event_type: ev.event_type,
      url: ev.meta?.url ?? '',
      ua: ev.meta?.ua ?? '',
      ip: ev.meta?.ip ?? '',
    }));
    const header = ['id','created_at','event_type','url','ua','ip'];
    const lines = [
      header.join(','),
      ...rows.map(r => [
        safeCSV(r.id),
        safeCSV(r.created_at),
        safeCSV(r.event_type),
        safeCSV(JSON.stringify(r.url)),
        safeCSV(JSON.stringify(r.ua)),
        safeCSV(JSON.stringify(r.ip))
      ].join(','))
    ];
    const blob = new Blob(["\ufeff" + lines.join('\n')], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `email_events_${activeLog?.id}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <AdminLayout>
      <Box p={6}>
        <Flex justify="space-between" align="center" mb={6} flexWrap="wrap" gap={4}>
          <Box>
            <Heading size="lg" mb={2}>
              Správa newsletteru
            </Heading>
            <Text color="gray.600">
              Spravujte odběratele newsletteru a rozesílejte hromadné zprávy
            </Text>
          </Box>
          <HStack spacing={3}>
            {selectedSubscribers.length > 0 && (
              <Button
                colorScheme="red"
                variant="outline"
                leftIcon={<DeleteIcon />}
                onClick={handleDeleteSelected}
                isLoading={deleteMutation.isLoading}
              >
                Smazat vybrané ({selectedSubscribers.length})
              </Button>
            )}
            <Button
              variant="outline"
              onClick={testModal.onOpen}
            >
              Odeslat testovací e-mail
            </Button>
            <Button variant="outline" onClick={smtpModal.onOpen}>Otestovat SMTP</Button>
            <Button
              colorScheme="blue"
              leftIcon={<EmailIcon />}
              onClick={onOpen}
              isDisabled={subscribers.length === 0}
            >
              Odeslat newsletter
            </Button>
          </HStack>
        </Flex>

        {/* Tabs layout */}
        <Tabs colorScheme="blue" isFitted>
          <TabList>
            <Tab>Stav</Tab>
            <Tab>Plánování</Tab>
            <Tab>Statistika</Tab>
          </TabList>
          <TabPanels>
            <TabPanel p={0}>
              {/* Status panel */}
              <Box bg={cardBg} borderRadius="lg" boxShadow="sm" p={4} mb={6}>
                <Heading size="md" mb={3}>Stav rozesílek</Heading>
                <HStack spacing={6} wrap="wrap">
                  <Text><b>Odběratelů:</b> {statusData?.total_subscribers ?? '—'}</Text>
                  <Text><b>Aktivních:</b> {statusData?.active_subscribers ?? '—'}</Text>
                  <Text><b>Další běh:</b> {statusData?.next_approximate ? format(new Date(statusData.next_approximate), 'd. M. yyyy HH:mm', { locale: cs }) : '—'}</Text>
                  <Text><b>Interval:</b> {statusData?.interval_minutes ? `${statusData.interval_minutes} min` : '—'}</Text>
                  <HStack>
                    <Switch size="sm" isChecked={!!statusData?.newsletter_enabled} onChange={(e)=> automationToggle.mutate(e.target.checked)} />
                    <Text>Automatické rozesílky</Text>
                  </HStack>
                </HStack>
                {statusData?.next_approximate ? (
                  <Text color="gray.600" fontSize="sm" mt={2}>
                    Další automatický newsletter za {(() => {
                      const diff = new Date(statusData.next_approximate).getTime() - Date.now();
                      if (diff <= 0) return 'méně než minutu';
                      const mins = Math.floor(diff / 60000);
                      const hrs = Math.floor(mins / 60);
                      const rem = mins % 60;
                      return hrs > 0 ? `${hrs} h ${rem} min` : `${mins} min`;
                    })()}
                  </Text>
                ) : null}
                {statusData?.sample_recipients?.length ? (
                  <Box mt={3}>
                    <Text color="gray.600" fontSize="sm">Ukázka příjemců ({statusData.sample_recipients.length}): {statusData.sample_recipients.join(', ')}</Text>
                  </Box>
                ) : null}
              </Box>
            </TabPanel>
            <TabPanel p={0}>
              {/* Scheduling controls */}
              <Box bg={cardBg} borderRadius="lg" boxShadow="sm" p={4} mb={6}>
                <Heading size="md" mb={3}>Plánování rozesílek</Heading>
                <Text color="gray.600" mb={4}>Nastavte, kdy se automaticky posílají jednotlivé typy newsletterů.</Text>
                {settingsQuery.isLoading ? (
                  <HStack color="gray.600"><Spinner size="sm" /> <Text>Načítám nastavení…</Text></HStack>
                ) : (
                  <VStack align="stretch" spacing={4}>
                    <HStack justify="space-between">
                      <Text fontWeight="600">Týdenní přehled</Text>
                      <Switch isChecked={enableWeekly} onChange={(e)=> setEnableWeekly(e.target.checked)} />
                    </HStack>
                    <HStack spacing={3}>
                      <FormControl maxW="220px">
                        <FormLabel>Den v týdnu</FormLabel>
                        <Select value={weeklyDay} onChange={(e)=> setWeeklyDay(e.target.value as any)}>
                          <option value="sun">Neděle</option>
                          <option value="mon">Pondělí</option>
                          <option value="tue">Úterý</option>
                          <option value="wed">Středa</option>
                          <option value="thu">Čtvrtek</option>
                          <option value="fri">Pátek</option>
                          <option value="sat">Sobota</option>
                        </Select>
                      </FormControl>
                      <FormControl maxW="160px">
                        <FormLabel>Hodina</FormLabel>
                        <Input type="number" min={0} max={23} value={weeklyHour} onChange={(e)=> setWeeklyHour(Math.max(0, Math.min(23, Number(e.target.value)||0)))} />
                      </FormControl>
                    </HStack>

                  </VStack>
                )}
              </Box>
            </TabPanel>

            {/* Analytics tab */}
            <TabPanel p={0}>
              <Box bg={cardBg} borderRadius="lg" boxShadow="sm" p={4} mb={6}>
                <Heading size="md" mb={3}>Dodání a interakce</Heading>
                {statsLoading ? (
                  <HStack color="gray.600"><Spinner size="sm" /> <Text>Načítám statistiky…</Text></HStack>
                ) : recentStats.length === 0 ? (
                  <Text color="gray.600">Zatím nejsou k dispozici žádné záznamy.</Text>
                ) : (
                  <Box overflowX="auto">
                    <Table size="sm" variant="simple">
                      <Thead>
                        <Tr>
                          <Th>Čas</Th>
                          <Th>Předmět</Th>
                          <Th>Příjemce</Th>
                          <Th isNumeric>Otevření</Th>
                          <Th isNumeric>Kliknutí</Th>
                          <Th isNumeric>Spam</Th>
                          <Th isNumeric>Odhlášení</Th>
                          <Th>Stav</Th>
                          <Th>Detail</Th>
                        </Tr>
                      </Thead>
                      <Tbody>
                        {recentStats.slice(0, 50).map((row) => (
                          <Tr key={row.id}>
                            <Td>{format(new Date(row.created_at), 'd. M. yyyy HH:mm', { locale: cs })}</Td>
                            <Td>{row.subject}</Td>
                            <Td>{row.recipient}</Td>
                            <Td isNumeric>{row.opens}</Td>
                            <Td isNumeric>{row.clicks}</Td>
                            <Td isNumeric>{row.spam}</Td>
                            <Td isNumeric>{row.unsubs}</Td>
                            <Td>
                              <Badge colorScheme={row.status === 'failed' ? 'red' : 'green'}>{row.status}</Badge>
                            </Td>
                            <Td>
                              <Button size="xs" variant="outline" onClick={() => { setActiveLog(row); setEventsModalOpen(true); }}>Detail</Button>
                            </Td>
                          </Tr>
                        ))}
                      </Tbody>
                    </Table>
                  </Box>
                )}
              </Box>
            </TabPanel>
          </TabPanels>
        </Tabs>

        {/* Subscribers table */}
        <Box bg={cardBg} borderRadius="lg" boxShadow="sm" p={4} mb={6}>
          <InputGroup maxW="md" mb={4}>
            <InputLeftElement pointerEvents="none">
              <SearchIcon color="gray.400" />
            </InputLeftElement>
            <Input
              placeholder="Hledat podle e-mailu..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </InputGroup>

          <Box overflowX="auto">
            <Table variant="simple">
              <Thead>
                <Tr>
                  <Th w="40px">
                    <input
                      type="checkbox"
                      onChange={handleSelectAll}
                      checked={
                        filteredSubscribers.length > 0 &&
                        selectedSubscribers.length === filteredSubscribers.length
                      }
                    />
                  </Th>
                  <Th>E-mail</Th>
                  <Th>Stav</Th>
                  <Th>Datum registrace</Th>
                  <Th>Poslední změna</Th>
                  <Th w="120px">Akce</Th>
                </Tr>
              </Thead>
              <Tbody>
                {isLoading ? (
                  <Tr>
                    <Td colSpan={6} textAlign="center" py={8}>
                      Načítání...
                    </Td>
                  </Tr>
                ) : filteredSubscribers.length === 0 ? (
                  <Tr>
                    <Td colSpan={6} textAlign="center" py={8} color="gray.500">
                      {searchTerm ? 'Žádní odběratelé nebyli nalezeni' : 'Žádní odběratelé'}
                    </Td>
                  </Tr>
                ) : (
                  filteredSubscribers.map((subscriber) => (
                    <Tr key={subscriber.id}>
                      <Td>
                        <input
                          type="checkbox"
                          checked={selectedSubscribers.includes(subscriber.id)}
                          onChange={(e) =>
                            handleSelectSubscriber(subscriber.id, e.target.checked)
                          }
                        />
                      </Td>
                      <Td>{subscriber.email}</Td>
                      <Td>
                        <Badge
                          colorScheme={subscriber.is_active ? 'green' : 'gray'}
                        >
                          {subscriber.is_active ? 'Aktivní' : 'Neaktivní'}
                        </Badge>
                      </Td>
                      <Td>
                        {(() => {
                          const prefs = (subscriber as any).preferences;
                          if (prefs && Object.keys(prefs).length > 0) {
                            return Object.keys(prefs).map((k) =>
                              prefs[k] ? <Badge key={k} mr={1} colorScheme="blue">{k}</Badge> : null
                            );
                          }
                          return <Text color="gray.500">Žádné</Text>;
                        })()}
                      </Td>
                      <Td>{formatDate(subscriber.created_at)}</Td>
                      <Td>{formatDate(subscriber.updated_at)}</Td>
                      <Td>
                        <HStack spacing={2}>
                          <Tooltip label={subscriber.is_active ? 'Deaktivovat' : 'Aktivovat'}>
                            <span>
                              <Switch
                                colorScheme="green"
                                isChecked={subscriber.is_active}
                                onChange={(e) =>
                                  toggleStatusMutation.mutate({
                                    id: subscriber.id,
                                    isActive: e.target.checked,
                                  })
                                }
                                isDisabled={toggleStatusMutation.isLoading}
                              />
                            </span>
                          </Tooltip>
                          <Tooltip label="Smazat">
                            <span>
                              <IconButton
                                aria-label="Smazat odběratele"
                                icon={<DeleteIcon />}
                                size="sm"
                                colorScheme="red"
                                variant="ghost"
                                onClick={() => {
                                  if (window.confirm('Opravdu chcete smazat tohoto odběratele?')) {
                                    deleteMutation.mutate(subscriber.id);
                                  }
                                }}
                                isLoading={
                                  deleteMutation.isLoading &&
                                  (deleteMutation as any).variables === subscriber.id
                                }
                              />
                            </span>
                          </Tooltip>
                          <Tooltip label="Upravit preference">
                            <Button
                              size="sm"
                              variant="ghost"
                              onClick={() => {
                                setEditingSubscriber(subscriber);
                                setEditingPrefs((subscriber as any).preferences || {});
                                setPrefsModalOpen(true);
                              }}
                            >
                              Upravit
                            </Button>
                          </Tooltip>
                        </HStack>
                      </Td>
                    </Tr>
                  ))
                )}
              </Tbody>
            </Table>
          </Box>
        </Box>
      </Box>

      {/* Send Newsletter Modal */}
      <Modal isOpen={isOpen} onClose={onClose} size="xl">
        <ModalOverlay />
        <ModalContent maxW="90vw" maxH="90vh" overflowY="auto">
          <ModalHeader>Odeslat newsletter</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            <VStack spacing={4} align="stretch">
              <Text>
                Newsletter bude odeslán všem aktivním odběratelům ({subscribers.filter(s => s.is_active).length}).
              </Text>

              <FormControl>
                <FormLabel>Typ</FormLabel>
                <Select value={sendMode} onChange={(e)=> setSendMode(e.target.value as any)}>
                  <option value="custom">Vlastní obsah</option>
                  <option value="matches">Šablona: Zápasy</option>
                  <option value="scores">Šablona: Výsledky</option>
                  <option value="events">Šablona: Akce</option>
                  <option value="blogs">Šablona: Novinky</option>
                  <option value="weekly">Šablona: Týdenní přehled</option>
                </Select>
                <FormHelperText>Zvolte mezi vlastním obsahem nebo automatickou šablonou.</FormHelperText>
              </FormControl>
              
              {sendMode === 'custom' && (
                <>
                  <FormControl isRequired>
                    <FormLabel>Předmět</FormLabel>
                    <Input
                      placeholder="Předmět zprávy"
                      value={newsletterData.subject}
                      onChange={(e) =>
                        setNewsletterData({ ...newsletterData, subject: e.target.value })
                      }
                    />
                  </FormControl>
              
                  <FormControl isRequired>
                    <FormLabel>Obsah zprávy</FormLabel>
                    <Textarea
                      placeholder="Zde napište obsah newsletteru..."
                      value={newsletterData.content}
                      onChange={(e) =>
                        setNewsletterData({ ...newsletterData, content: e.target.value })
                      }
                      rows={10}
                    />
                    <FormHelperText>
                      Pro formátování textu můžete použít HTML značky.
                    </FormHelperText>
                  </FormControl>
                </>
              )}

              {sendMode !== 'custom' && (
                <>
                  <FormControl>
                    <FormLabel>Filtr soutěží (volitelné)</FormLabel>
                    <Input placeholder="NAPŘ. KP, I.A, I.B" value={competitions} onChange={(e)=> setCompetitions(e.target.value)} />
                    <FormHelperText>Čárkou oddělený seznam kódů soutěží.</FormHelperText>
                  </FormControl>
                  <HStack>
                    <Button variant="outline" onClick={async ()=>{
                      setPreviewLoading(true);
                      try {
                        const prefs: any = {};
                        if (sendMode === 'weekly') { prefs.blogs = true; prefs.events = true; prefs.matches = true; prefs.scores = true; } else { (prefs as any)[sendMode] = true; }
                        if (competitions.trim()) { prefs.competitions = competitions.trim(); }
                        const res = await previewNewsletter({ preferences: prefs });
                        setPreviewSubject(res.subject);
                        setPreviewHtml(res.html);
                      } finally {
                        setPreviewLoading(false);
                      }
                    }}>Náhled šablony</Button>
                    {previewLoading && <Spinner size="sm" />}
                    {previewSubject && <Badge colorScheme="blue">{previewSubject}</Badge>}
                  </HStack>
                  <Box mt={2} p={3} bg={useColorModeValue('gray.50', 'gray.900')} borderRadius="md" borderWidth="1px">
                    <Box
                      bg={cardBg}
                      p={3}
                      borderRadius="md"
                      borderWidth="1px"
                      dangerouslySetInnerHTML={{ __html: sanitizeHtml(previewHtml || '<em>Náhled se zobrazí zde</em>') }}
                    />
                  </Box>
                </>
              )}
              
              <Box mt={4} p={4} bg={useColorModeValue('gray.50', 'gray.900')} borderRadius="md">
                <Text fontWeight="bold" mb={2}>Náhled:</Text>
                <Box
                  border="1px"
                  borderColor="gray.200"
                  p={4}
                  borderRadius="md"
                  bg={cardBg}
                  dangerouslySetInnerHTML={{ __html: sanitizeHtml(sendMode === 'custom' ? (newsletterData.content || '<em>Náhled se zobrazí zde</em>') : (previewHtml || '<em>Náhled se zobrazí zde</em>')) }}
                />
              </Box>
            </VStack>
          </ModalBody>
          <ModalFooter>
            <Button variant="ghost" mr={3} onClick={onClose}>
              Zrušit
            </Button>
            {sendMode === 'custom' ? (
              <Button
                colorScheme="blue"
                onClick={handleSendNewsletter}
                isLoading={sendNewsletterMutation.isLoading}
                isDisabled={!newsletterData.subject || !newsletterData.content}
                leftIcon={<EmailIcon />}
              >
                Odeslat newsletter
              </Button>
            ) : (
              <Button
                colorScheme="blue"
                onClick={async ()=>{
                  try {
                    await sendNewsletterDigest(sendMode as DigestType, competitions.trim() || undefined);
                    toast({ title: 'Digest odeslán', status: 'success' });
                    onClose();
                    setPreviewHtml(''); setPreviewSubject(''); setCompetitions(''); setSendMode('custom');
                  } catch (e: any) {
                    toast({ title: 'Chyba při odeslání', description: e?.response?.data?.error || e?.message, status: 'error' });
                  }
                }}
                leftIcon={<EmailIcon />}
              >
                Odeslat digest
              </Button>
            )}
          </ModalFooter>
        </ModalContent>
      </Modal>

      {/* Test Email Modal */}
      <Modal isOpen={testModal.isOpen} onClose={testModal.onClose} size="md">
        <ModalOverlay />
        <ModalContent maxW="90vw" maxH="90vh" overflowY="auto">
          <ModalHeader>Odeslat testovací e-mail</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            <VStack spacing={4} align="stretch">
              <Text color="gray.600">
                Testovací e-mail bude odeslán na zadanou adresu. Pokud pole necháte prázdné, odešleme na výchozí administrátorský e-mail.
              </Text>
              <FormControl>
                <FormLabel>E-mail příjemce (volitelně)</FormLabel>
                <Input
                  type="email"
                  placeholder="např. admin@priklad.cz"
                  value={testEmail}
                  onChange={(e) => setTestEmail(e.target.value)}
                />
              </FormControl>
              <FormControl>
                <FormLabel>Více e-mailů (oddělené čárkou)</FormLabel>
                <Input
                  placeholder="user1@priklad.cz, user2@priklad.cz"
                  value={testEmails}
                  onChange={(e) => setTestEmails(e.target.value)}
                />
                <FormHelperText>Pokud vyplníte, použije se toto pole přednostně.</FormHelperText>
              </FormControl>
              <FormControl>
                <FormLabel>Typ testu</FormLabel>
                <select value={testType} onChange={(e) => setTestType(e.target.value as NewsletterTestType)}>
                  <option value="newsletter">Newsletter</option>
                  <option value="welcome">Uvítací</option>
                  <option value="welcome_back">Uvítací (návrat)</option>
                  <option value="blogs">Blogy (digest)</option>
                  <option value="events">Události (digest)</option>
                  <option value="matches">Zápasy (digest)</option>
                  <option value="scores">Výsledky (digest)</option>
                  <option value="weekly">Týdenní přehled</option>
                </select>
              </FormControl>
            </VStack>
          </ModalBody>
          <ModalFooter>
            <Button variant="ghost" mr={3} onClick={testModal.onClose}>
              Zavřít
            </Button>
            <Button colorScheme="blue" onClick={() => sendTestMutation.mutate()} isLoading={sendTestMutation.isLoading}>
              Odeslat test
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>

      {/* Preferences Modal */}
      <Modal isOpen={prefsModalOpen} onClose={() => setPrefsModalOpen(false)} size="md">
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>Upravit preference</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            <VStack spacing={4} align="stretch">
              <FormControl>
                <FormLabel>Týdenní přehled</FormLabel>
                <Switch isChecked={!!editingPrefs['weekly']} onChange={(e) => setEditingPrefs({ ...editingPrefs, weekly: e.target.checked })} />
              </FormControl>
              <FormControl>
                <FormLabel>Nadcházející zápasy</FormLabel>
                <Switch isChecked={!!editingPrefs['matches']} onChange={(e) => setEditingPrefs({ ...editingPrefs, matches: e.target.checked })} />
              </FormControl>
              <FormControl>
                <FormLabel>Blog</FormLabel>
                <Switch isChecked={!!editingPrefs['blogs']} onChange={(e) => setEditingPrefs({ ...editingPrefs, blogs: e.target.checked })} />
              </FormControl>
            </VStack>
          </ModalBody>
          <ModalFooter>
            <Button variant="ghost" mr={3} onClick={() => setPrefsModalOpen(false)}>Zrušit</Button>
            <Button
              colorScheme="blue"
              onClick={() =>
                editingSubscriber
                  ? updatePrefsMutation.mutate({ id: editingSubscriber.id, prefs: editingPrefs })
                  : undefined
              }
              isLoading={updatePrefsMutation.isLoading}
              isDisabled={!editingSubscriber}
            >
              Uložit
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </AdminLayout>
  );
}
