import React, { useState, useEffect } from 'react';
import {
  Box,
  Button,
  Table,
  Thead,
  Tbody,
  Tr,
  Th,
  Td,
  IconButton,
  useToast,
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalCloseButton,
  ModalBody,
  ModalFooter,
  FormControl,
  FormLabel,
  Input,
  Textarea,
  Switch,
  Select,
  Tabs,
  TabList,
  TabPanels,
  Tab,
  TabPanel,
  Heading,
  Text,
  Badge,
  HStack,
  VStack,
  useDisclosure,
  AlertDialog,
  AlertDialogBody,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogContent,
  AlertDialogOverlay,
  SimpleGrid,
  Divider,
  FormHelperText,
  useColorModeValue,
} from '@chakra-ui/react';
import { FiEdit, FiTrash2, FiPlus, FiUser } from 'react-icons/fi';
import AdminLayout from '../../layouts/AdminLayout';
import {
  getContacts,
  createContact,
  updateContact,
  deleteContact,
  Contact,
  getContactCategories,
  ContactCategory,
} from '../../services/contactInfo';
import api, { uploadImage } from '../../services/api';
import { getImageUrl } from '../../utils/imageUtils';
import { getAdminSettings, updateAdminSettings, AdminSettings, PublicSettings } from '../../services/settings';
import MapLinkImporter from '../../components/admin/MapLinkImporter';
import { MapCoordinates } from '../../utils/mapUrlParser';
import ContactMap from '../../components/home/ContactMap';
import MapStyleSelector from '../../components/admin/MapStyleSelector';

const ContactsAdminPage: React.FC = () => {
  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 bgMain = useColorModeValue('gray.50', 'gray.900');
  const tableBg = useColorModeValue('white', 'gray.800');
  const hoverBg = useColorModeValue('gray.50', 'gray.700');
  const infoBg = useColorModeValue('blue.50', 'blue.900');
  const infoBorder = useColorModeValue('blue.200', 'blue.700');
  const [contacts, setContacts] = useState<Contact[]>([]);
  const [categories, setCategories] = useState<ContactCategory[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedContact, setSelectedContact] = useState<Contact | null>(null);
  const [isContactModalOpen, setIsContactModalOpen] = useState(false);
  const [deleteItem, setDeleteItem] = useState<{ type: 'contact'; id: number } | null>(null);
  const cancelRef = React.useRef<HTMLButtonElement>(null);
  const toast = useToast();

  // Form states
  const [contactForm, setContactForm] = useState({
    name: '',
    position: '',
    email: '',
    phone: '',
    category_id: undefined as number | undefined,
    image_url: '',
    description: '',
    display_order: 0,
    is_active: true,
  });


  const [uploadingImage, setUploadingImage] = useState(false);
  const [settings, setSettings] = useState<AdminSettings>({});
  const [savingSettings, setSavingSettings] = useState(false);

  useEffect(() => {
    loadData();
    loadSettings();
  }, []);

  const loadData = async () => {
    setLoading(true);
    try {
      const [contactsData, categoriesData] = await Promise.all([
        getContacts(),
        getContactCategories(),
      ]);
      setContacts(contactsData);
      setCategories(categoriesData);
    } catch (error) {
      toast({
        title: 'Chyba při načítání',
        description: 'Nepodařilo se načíst kontakty a kategorie',
        status: 'error',
        duration: 3000,
      });
    } finally {
      setLoading(false);
    }
  };

  // Contact handlers
  const openContactModal = (contact?: Contact) => {
    if (contact) {
      setSelectedContact(contact);
      setContactForm({
        name: contact.name,
        position: contact.position,
        email: contact.email,
        phone: contact.phone,
        category_id: contact.category_id,
        image_url: contact.image_url || '',
        description: contact.description || '',
        display_order: contact.display_order,
        is_active: contact.is_active,
      });
    } else {
      setSelectedContact(null);
      setContactForm({
        name: '',
        position: '',
        email: '',
        phone: '',
        category_id: undefined,
        image_url: '',
        description: '',
        display_order: contacts.length * 10,
        is_active: true,
      });
    }
    setIsContactModalOpen(true);
  };

  const loadSettings = async () => {
    try {
      const data = await getAdminSettings();
      setSettings(data || {});
    } catch (error) {
      console.error('Failed to load settings:', error);
    }
  };

  const handleSettingsChange = (key: keyof AdminSettings) => (e: React.ChangeEvent<HTMLInputElement>) => {
    setSettings((prev) => ({ ...prev, [key]: e.target.value }));
  };

  const handleNumChange = (key: keyof AdminSettings) => (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.value;
    const n = val === '' ? undefined : Number(val);
    setSettings((prev) => ({ ...prev, [key]: (Number.isFinite(n as number) ? (n as any) : undefined) }));
  };

  const handleBoolChange = (key: keyof AdminSettings) => (e: React.ChangeEvent<HTMLInputElement>) => {
    const checked = (e.target as any).checked as boolean;
    setSettings((prev) => ({ ...prev, [key]: checked as any }));
  };

  const handleSelectChange = (key: keyof AdminSettings) => (e: React.ChangeEvent<HTMLSelectElement>) => {
    setSettings((prev) => ({ ...prev, [key]: e.target.value }));
  };

  const handleSaveSettings = async () => {
    setSavingSettings(true);
    try {
      // Extract and validate settings
      const lat = typeof settings.location_latitude === 'number' ? settings.location_latitude : undefined;
      const lng = typeof settings.location_longitude === 'number' ? settings.location_longitude : undefined;
      const zoom = typeof settings.map_zoom_level === 'number' ? settings.map_zoom_level : undefined;
      
      // Auto-enable map display if coordinates are set
      const hasCoordinates = lat !== undefined && lng !== undefined;
      
      // Build payload with proper types, filtering out undefined values
      const payload: Partial<AdminSettings> = {};
      
      if (settings.contact_address !== undefined) payload.contact_address = settings.contact_address;
      if (settings.contact_city !== undefined) payload.contact_city = settings.contact_city;
      if (settings.contact_zip !== undefined) payload.contact_zip = settings.contact_zip;
      if (settings.contact_country !== undefined) payload.contact_country = settings.contact_country;
      if (settings.contact_phone !== undefined) payload.contact_phone = settings.contact_phone;
      if (settings.contact_email !== undefined) payload.contact_email = settings.contact_email;
      if (lat !== undefined) payload.location_latitude = lat;
      if (lng !== undefined) payload.location_longitude = lng;
      if (zoom !== undefined) payload.map_zoom_level = zoom;
      if (settings.map_style !== undefined) payload.map_style = settings.map_style;
      payload.show_map_on_homepage = hasCoordinates;
      
      await updateAdminSettings(payload);
      toast({
        title: 'Nastavení uloženo',
        description: 'Kontaktní informace a mapa byly aktualizovány',
        status: 'success',
        duration: 3000,
      });
    } catch (error: any) {
      const errorMsg = error?.response?.data?.chyba || error?.response?.data?.detail || error?.response?.data?.error || error?.message || 'Uložení nastavení se nezdařilo';
      console.error('Settings save error:', error);
      toast({
        title: 'Chyba při ukládání',
        description: errorMsg,
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    } finally {
      setSavingSettings(false);
    }
  };

  const handleContactSubmit = async () => {
    if (!contactForm.name.trim()) {
      toast({
        title: 'Chyba validace',
        description: 'Jméno je povinné',
        status: 'error',
        duration: 3000,
      });
      return;
    }

    setLoading(true);
    try {
      if (selectedContact) {
        await updateContact(selectedContact.id, contactForm);
        toast({
          title: 'Kontakt aktualizován',
          status: 'success',
          duration: 2000,
        });
      } else {
        await createContact(contactForm);
        toast({
          title: 'Kontakt vytvořen',
          status: 'success',
          duration: 2000,
        });
      }
      setIsContactModalOpen(false);
      loadData();
    } catch (error: any) {
      toast({
        title: 'Chyba',
        description: error.response?.data?.error || 'Uložení kontaktu se nezdařilo',
        status: 'error',
        duration: 3000,
      });
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteContact = async (id: number) => {
    setLoading(true);
    try {
      await deleteContact(id);
      toast({
        title: 'Kontakt smazán',
        status: 'success',
        duration: 2000,
      });
      loadData();
    } catch (error) {
      toast({
        title: 'Chyba',
        description: 'Smazání kontaktu se nezdařilo',
        status: 'error',
        duration: 3000,
      });
    } finally {
      setLoading(false);
      setDeleteItem(null);
    }
  };


  // Image upload handler
  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // Validate file type
    if (!file.type.startsWith('image/')) {
      toast({
        title: 'Neplatný typ souboru',
        description: 'Nahrajte prosím obrázkový soubor',
        status: 'error',
        duration: 3000,
      });
      return;
    }

    setUploadingImage(true);
    try {
      const formData = new FormData();
      formData.append('file', file);

      const result = await uploadImage(formData);
      setContactForm({ ...contactForm, image_url: result.url });
      toast({
        title: 'Obrázek nahrán',
        status: 'success',
        duration: 2000,
      });
    } catch (error: any) {
      toast({
        title: 'Nahrávání selhalo',
        description: error.response?.data?.error || 'Nahrání obrázku se nezdařilo',
        status: 'error',
        duration: 3000,
      });
    } finally {
      setUploadingImage(false);
    }
  };

  return (
    <AdminLayout>
      <Box p={6} bg={bgMain} minH="100vh">
        <Heading size="lg" mb={6}>Správa kontaktů</Heading>

        <Tabs colorScheme="blue">
          <TabList>
            <Tab>Kontakty</Tab>
            <Tab>Mapa a adresa</Tab>
          </TabList>

          <TabPanels>
            {/* Contacts Tab */}
            <TabPanel>
              <HStack justify="space-between" mb={4}>
                <Text>Spravujte kontaktní osoby vašeho klubu</Text>
                <Button
                  leftIcon={<FiPlus />}
                  colorScheme="blue"
                  onClick={() => openContactModal()}
                >
                  Přidat kontakt
                </Button>
              </HStack>

              <Box overflowX="auto" bg={tableBg} borderRadius="md" borderWidth="1px" borderColor={borderColor}>
                <Table variant="simple">
                  <Thead>
                    <Tr>
                      <Th>Foto</Th>
                      <Th>Jméno</Th>
                      <Th>Pozice</Th>
                      <Th>Soutěž</Th>
                      <Th>Email</Th>
                      <Th>Telefon</Th>
                      <Th>Pořadí</Th>
                      <Th>Stav</Th>
                      <Th>Akce</Th>
                    </Tr>
                  </Thead>
                  <Tbody>
                    {contacts.map((contact) => (
                      <Tr key={contact.id}>
                        <Td>
                          {contact.image_url ? (
                            <Box
                              as="img"
                              src={getImageUrl(contact.image_url)}
                              alt={contact.name}
                              boxSize="40px"
                              objectFit="cover"
                              borderRadius="md"
                            />
                          ) : (
                            <Box
                              boxSize="40px"
                              bg="gray.200"
                              borderRadius="md"
                              display="flex"
                              alignItems="center"
                              justifyContent="center"
                            >
                              <FiUser />
                            </Box>
                          )}
                        </Td>
                        <Td fontWeight="bold">{contact.name}</Td>
                        <Td>{contact.position}</Td>
                        <Td>
                          {contact.category_id ? (
                            <Badge colorScheme="purple">{categories.find(c => c.id === contact.category_id)?.name || contact.category_id}</Badge>
                          ) : (
                            <Text fontSize="sm" color="gray.500">Bez kategorie</Text>
                          )}
                        </Td>
                        <Td>{contact.email}</Td>
                        <Td>{contact.phone}</Td>
                        <Td>{contact.display_order}</Td>
                        <Td>
                          <Badge colorScheme={contact.is_active ? 'green' : 'red'}>
                            {contact.is_active ? 'Aktivní' : 'Neaktivní'}
                          </Badge>
                        </Td>
                        <Td>
                          <HStack spacing={2}>
                            <IconButton
                              aria-label="Upravit"
                              icon={<FiEdit />}
                              size="sm"
                              onClick={() => openContactModal(contact)}
                            />
                            <IconButton
                              aria-label="Smazat"
                              icon={<FiTrash2 />}
                              size="sm"
                              colorScheme="red"
                              onClick={() => setDeleteItem({ type: 'contact', id: contact.id })}
                            />
                          </HStack>
                        </Td>
                      </Tr>
                    ))}
                    {contacts.length === 0 && (
                      <Tr>
                        <Td colSpan={9} textAlign="center" py={8}>
                          <Text color="gray.500">Zatím žádné kontakty. Přidejte svůj první kontakt!</Text>
                        </Td>
                      </Tr>
                    )}
                  </Tbody>
                </Table>
              </Box>
            </TabPanel>

            {/* Map & Address Tab */}
            <TabPanel>
              <VStack align="stretch" spacing={6}>
                <Box bg={cardBg} p={6} borderRadius="lg" borderWidth="1px" borderColor={borderColor}>
                  <Heading size="md" mb={4}>Kontaktní údaje</Heading>
                  <SimpleGrid columns={{ base: 1, md: 2 }} spacing={4}>
                    <FormControl>
                      <FormLabel>Adresa</FormLabel>
                      <Input
                        bg={inputBg}
                        value={settings.contact_address || ''}
                        onChange={handleSettingsChange('contact_address' as keyof AdminSettings)}
                        placeholder="Ulice a č.p."
                      />
                    </FormControl>
                    <FormControl>
                      <FormLabel>Město</FormLabel>
                      <Input
                        bg={inputBg}
                        value={settings.contact_city || ''}
                        onChange={handleSettingsChange('contact_city' as keyof AdminSettings)}
                        placeholder="Město"
                      />
                    </FormControl>
                    <FormControl>
                      <FormLabel>PSČ</FormLabel>
                      <Input
                        bg={inputBg}
                        value={settings.contact_zip || ''}
                        onChange={handleSettingsChange('contact_zip' as keyof AdminSettings)}
                        placeholder="12345"
                      />
                    </FormControl>
                    <FormControl>
                      <FormLabel>Země</FormLabel>
                      <Input
                        bg={inputBg}
                        value={settings.contact_country || ''}
                        onChange={handleSettingsChange('contact_country' as keyof AdminSettings)}
                        placeholder="Česká republika"
                      />
                    </FormControl>
                    <FormControl>
                      <FormLabel>Telefon</FormLabel>
                      <Input
                        bg={inputBg}
                        value={settings.contact_phone || ''}
                        onChange={handleSettingsChange('contact_phone' as keyof AdminSettings)}
                        placeholder="+420 123 456 789"
                      />
                    </FormControl>
                    <FormControl>
                      <FormLabel>E-mail</FormLabel>
                      <Input
                        bg={inputBg}
                        type="email"
                        value={settings.contact_email || ''}
                        onChange={handleSettingsChange('contact_email' as keyof AdminSettings)}
                        placeholder="kontakt@klub.cz"
                      />
                    </FormControl>
                  </SimpleGrid>
                </Box>

                <Box bg={cardBg} p={6} borderRadius="lg" borderWidth="1px" borderColor={borderColor}>
                  <Heading size="md" mb={4}>Poloha na mapě</Heading>
                  <MapLinkImporter
                    currentLatitude={settings.location_latitude}
                    currentLongitude={settings.location_longitude}
                    currentZoom={settings.map_zoom_level}
                    mapStyle={settings.map_style || 'positron'}
                    clubPrimaryColor={settings.primary_color}
                    clubSecondaryColor={settings.accent_color}
                    clubName={settings.club_name}
                    onImport={(coords: MapCoordinates) => {
                      setSettings((prev) => ({
                        ...prev,
                        location_latitude: coords.latitude,
                        location_longitude: coords.longitude,
                        map_zoom_level: coords.zoom,
                        // Auto-fill address fields if available
                        contact_address: coords.street || prev.contact_address,
                        contact_city: coords.city || prev.contact_city,
                        contact_zip: coords.zip || prev.contact_zip,
                        contact_country: coords.country || prev.contact_country,
                      }));
                      toast({
                        title: 'Souřadnice a adresa importovány',
                        description: `GPS poloha${coords.city ? ' a kontaktní údaje' : ''} byly načteny`,
                        status: 'success',
                        duration: 3000,
                      });
                    }}
                  />

                  <Text fontSize="sm" color={textSecondary} mt={2} fontStyle="italic">
                    Mapa se automaticky zobrazí na titulní stránce při nastavení GPS souřadnic.
                  </Text>
                </Box>

                <Box bg={cardBg} p={6} borderRadius="lg" borderWidth="1px" borderColor={borderColor}>
                  <Heading size="md" mb={4}>Ruční nastavení souřadnic</Heading>
                  <SimpleGrid columns={{ base: 1, md: 3 }} spacing={4}>
                    <FormControl>
                      <FormLabel>Zeměpisná šířka (Latitude)</FormLabel>
                      <Input
                        bg={inputBg}
                        type="number"
                        step="0.000001"
                        value={settings.location_latitude ?? ''}
                        onChange={handleNumChange('location_latitude' as keyof AdminSettings)}
                        placeholder="50.0947"
                      />
                      <FormHelperText fontSize="xs">Rozsah: -90 až 90</FormHelperText>
                    </FormControl>
                    <FormControl>
                      <FormLabel>Zeměpisná délka (Longitude)</FormLabel>
                      <Input
                        bg={inputBg}
                        type="number"
                        step="0.000001"
                        value={settings.location_longitude ?? ''}
                        onChange={handleNumChange('location_longitude' as keyof AdminSettings)}
                        placeholder="17.6997"
                      />
                      <FormHelperText fontSize="xs">Rozsah: -180 až 180</FormHelperText>
                    </FormControl>
                    <FormControl>
                      <FormLabel>Úroveň přiblížení (Zoom)</FormLabel>
                      <Input
                        bg={inputBg}
                        type="number"
                        min="1"
                        max="20"
                        value={settings.map_zoom_level ?? 15}
                        onChange={handleNumChange('map_zoom_level' as keyof AdminSettings)}
                        placeholder="15"
                      />
                      <FormHelperText fontSize="xs">Rozsah: 1-20 (vyšší = větší přiblížení)</FormHelperText>
                    </FormControl>
                  </SimpleGrid>
                </Box>

                <Box bg={cardBg} p={6} borderRadius="lg" borderWidth="1px" borderColor={borderColor}>
                  <MapStyleSelector
                    value={settings.map_style || 'positron'}
                    onChange={(value) => {
                      setSettings((prev) => ({ ...prev, map_style: value as PublicSettings['map_style'] }));
                    }}
                    clubPrimaryColor={settings.primary_color}
                    clubSecondaryColor={settings.accent_color}
                    showPreview={true}
                  />
                </Box>

                {/* Live Map Preview with Current Coordinates */}
                {settings.location_latitude && settings.location_longitude && (
                  <Box bg={cardBg} p={6} borderRadius="lg" borderWidth="1px" borderColor={borderColor}>
                    <VStack align="stretch" spacing={3}>
                      <HStack justify="space-between">
                        <Heading size="md">Náhled vaší mapy</Heading>
                        <Badge colorScheme="green">Aktuální poloha</Badge>
                      </HStack>
                      <Text fontSize="sm" color={textSecondary}>
                        Toto je náhled mapy s vaší aktuální polohou a vybraným stylem. Takto se zobrazí návštěvníkům na webu.
                      </Text>
                      <ContactMap
                        latitude={settings.location_latitude}
                        longitude={settings.location_longitude}
                        zoom={settings.map_zoom_level || 15}
                        address={`${settings.contact_address || ''}${settings.contact_city ? ', ' + settings.contact_city : ''}`}
                        clubName={settings.club_name}
                        mapStyle={settings.map_style || 'positron'}
                        clubPrimaryColor={settings.primary_color}
                        clubSecondaryColor={settings.accent_color}
                        height={400}
                      />
                    </VStack>
                  </Box>
                )}

                <Box bg={infoBg} p={4} borderRadius="md" borderWidth="1px" borderColor={infoBorder}>
                  <HStack justify="space-between" align="center">
                    <VStack align="start" spacing={1}>
                      <Text fontSize="sm" fontWeight="semibold">
                        📍 Nezapomeňte uložit změny
                      </Text>
                      <Text fontSize="xs" color={textSecondary}>
                        Uložte nastavení, aby se změny projevily na webu.
                      </Text>
                    </VStack>
                    <Button
                      colorScheme="blue"
                      size="lg"
                      onClick={handleSaveSettings}
                      isLoading={savingSettings}
                      loadingText="Ukládám..."
                    >
                      Uložit nastavení
                    </Button>
                  </HStack>
                </Box>
              </VStack>
            </TabPanel>
          </TabPanels>
        </Tabs>

        {/* Contact Modal */}
        <Modal isOpen={isContactModalOpen} onClose={() => setIsContactModalOpen(false)} size="xl">
          <ModalOverlay />
          <ModalContent>
            <ModalHeader>{selectedContact ? 'Upravit kontakt' : 'Přidat kontakt'}</ModalHeader>
            <ModalCloseButton />
            <ModalBody>
              <VStack spacing={4}>
                <FormControl isRequired>
                  <FormLabel>Jméno</FormLabel>
                  <Input
                    value={contactForm.name}
                    onChange={(e) => setContactForm({ ...contactForm, name: e.target.value })}
                    placeholder="Jan Novák"
                  />
                </FormControl>

                <FormControl>
                  <FormLabel>Pozice</FormLabel>
                  <Input
                    value={contactForm.position}
                    onChange={(e) => setContactForm({ ...contactForm, position: e.target.value })}
                    placeholder="Předseda, Hlavní trenér, atd."
                  />
                </FormControl>

                <FormControl>
                  <FormLabel>Kategorie</FormLabel>
                  <Select
                    value={contactForm.category_id || ''}
                    onChange={(e) =>
                      setContactForm({
                        ...contactForm,
                        category_id: e.target.value ? parseInt(e.target.value) : undefined,
                      })
                    }
                  >
                    <option value="">Bez přiřazení</option>
                    {categories.map((cat) => (
                      <option key={cat.id} value={cat.id}>
                        {cat.name}
                      </option>
                    ))}
                  </Select>
                  <FormHelperText fontSize="xs">Přiřaďte kontakt ke konkrétní kategorii</FormHelperText>
                </FormControl>

                <FormControl>
                  <FormLabel>Email</FormLabel>
                  <Input
                    type="email"
                    value={contactForm.email}
                    onChange={(e) => setContactForm({ ...contactForm, email: e.target.value })}
                    placeholder="john@example.com"
                  />
                </FormControl>

                <FormControl>
                  <FormLabel>Telefon</FormLabel>
                  <Input
                    value={contactForm.phone}
                    onChange={(e) => setContactForm({ ...contactForm, phone: e.target.value })}
                    placeholder="+420 123 456 789"
                  />
                </FormControl>

                <FormControl>
                  <FormLabel>Fotografie</FormLabel>
                  <Input
                    type="file"
                    accept="image/*"
                    onChange={handleImageUpload}
                    disabled={uploadingImage}
                  />
                  {contactForm.image_url && (
                    <Box mt={2}>
                      <img
                        src={getImageUrl(contactForm.image_url)}
                        alt="Náhled"
                        style={{ maxWidth: '200px', borderRadius: '8px' }}
                      />
                    </Box>
                  )}
                </FormControl>

                <FormControl>
                  <FormLabel>Popis</FormLabel>
                  <Textarea
                    value={contactForm.description}
                    onChange={(e) => setContactForm({ ...contactForm, description: e.target.value })}
                    placeholder="Stručný popis nebo bio"
                    rows={3}
                  />
                </FormControl>

                <FormControl>
                  <FormLabel>Pořadí zobrazení</FormLabel>
                  <Input
                    type="number"
                    value={contactForm.display_order}
                    onChange={(e) =>
                      setContactForm({ ...contactForm, display_order: parseInt(e.target.value) || 0 })
                    }
                  />
                </FormControl>

                <FormControl display="flex" alignItems="center">
                  <FormLabel mb="0">Aktivní</FormLabel>
                  <Switch
                    isChecked={contactForm.is_active}
                    onChange={(e) => setContactForm({ ...contactForm, is_active: e.target.checked })}
                  />
                </FormControl>
              </VStack>
            </ModalBody>
            <ModalFooter>
              <Button variant="ghost" mr={3} onClick={() => setIsContactModalOpen(false)}>
                Zrušit
              </Button>
              <Button colorScheme="blue" onClick={handleContactSubmit} isLoading={loading}>
                {selectedContact ? 'Aktualizovat' : 'Vytvořit'}
              </Button>
            </ModalFooter>
          </ModalContent>
        </Modal>

        {/* Delete Confirmation Dialog */}
        <AlertDialog
          isOpen={deleteItem !== null}
          leastDestructiveRef={cancelRef}
          onClose={() => setDeleteItem(null)}
        >
          <AlertDialogOverlay>
            <AlertDialogContent>
              <AlertDialogHeader fontSize="lg" fontWeight="bold">
                Smazat kontakt
              </AlertDialogHeader>

              <AlertDialogBody>
                Opravdu chcete smazat tento kontakt? Tuto akci nelze vrátit zpět.
              </AlertDialogBody>

              <AlertDialogFooter>
                <Button ref={cancelRef} onClick={() => setDeleteItem(null)}>
                  Zrušit
                </Button>
                <Button
                  colorScheme="red"
                  onClick={() => {
                    if (deleteItem) {
                      handleDeleteContact(deleteItem.id);
                    }
                  }}
                  ml={3}
                  isLoading={loading}
                >
                  Smazat
                </Button>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialogOverlay>
        </AlertDialog>
      </Box>
    </AdminLayout>
  );
};

export default ContactsAdminPage;
