import React, { useEffect, useState } from 'react';
import {
  Box,
  Container,
  Heading,
  Text,
  SimpleGrid,
  VStack,
  HStack,
  Avatar,
  Badge,
  Link,
  Icon,
  useColorModeValue,
  Divider,
  Accordion,
  AccordionItem,
  AccordionButton,
  AccordionPanel,
  AccordionIcon,
} from '@chakra-ui/react';
import { FiMail, FiPhone, FiMapPin } from 'react-icons/fi';
import { getPublicContacts, GroupedContacts } from '../../services/contactInfo';
import { getPublicSettings } from '../../services/settings';
import ContactMap from './ContactMap';
import { getImageUrl } from '../../utils/imageUtils';

const ContactsSection: React.FC = () => {
  const [contactsData, setContactsData] = useState<GroupedContacts | null>(null);
  const [settings, setSettings] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  const bgColor = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.700');

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

  const loadData = async () => {
    try {
      const [contacts, settingsData] = await Promise.all([
        getPublicContacts(),
        getPublicSettings(),
      ]);
      setContactsData(contacts);
      setSettings(settingsData);
    } catch (error) {
      console.error('Failed to load contacts:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading || !contactsData) {
    return null;
  }

  // Check if there's any data to display
  const hasContacts = Object.keys(contactsData.categories).length > 0 || contactsData.uncategorized.length > 0;
  const hasLocation = settings?.location_latitude && settings?.location_longitude;
  const hasContactInfo = settings?.contact_address || settings?.contact_phone || settings?.contact_email;

  if (!hasContacts && !hasLocation && !hasContactInfo) {
    return null; // Don't render if no data
  }

  return (
    <Box py={16} bg={useColorModeValue('gray.50', 'gray.900')}>
      <Container maxW="container.xl">
        <VStack spacing={8} align="stretch">
          <Box textAlign="center">
            <Heading size="xl" mb={4}>Kontakt</Heading>
            <Text fontSize="lg" color="gray.600">
              Spojte se s námi
            </Text>
          </Box>

          {/* Map and Address Section */}
          {(hasLocation || hasContactInfo) && (
            <SimpleGrid columns={{ base: 1, md: 2 }} spacing={8}>
              {/* Map - always show if coordinates are set */}
              {hasLocation && (
                <Box>
                  <ContactMap
                    latitude={settings.location_latitude}
                    longitude={settings.location_longitude}
                    zoom={settings.map_zoom_level || 15}
                    address={settings.contact_address}
                    clubName={settings.club_name || settings.site_title}
                    mapStyle={settings.map_style || 'default'}
                    clubPrimaryColor={settings.primary_color}
                    clubSecondaryColor={settings.accent_color}
                  />
                </Box>
              )}

              {/* Contact Information */}
              {hasContactInfo && (
                <Box
                  bg={bgColor}
                  p={6}
                  borderRadius="lg"
                  boxShadow="md"
                  border="1px"
                  borderColor={borderColor}
                >
                  <VStack align="stretch" spacing={4}>
                    <Heading size="md">Naše adresa</Heading>

                    {settings.contact_address && (
                      <HStack align="start">
                        <Icon as={FiMapPin} boxSize={5} color="blue.500" mt={1} />
                        <VStack align="start" spacing={0}>
                          <Text fontWeight="bold">Adresa</Text>
                          <Text>{settings.contact_address}</Text>
                          {settings.contact_city && (
                            <Text>
                              {settings.contact_zip && `${settings.contact_zip} `}
                              {settings.contact_city}
                            </Text>
                          )}
                          {settings.contact_country && <Text>{settings.contact_country}</Text>}
                        </VStack>
                      </HStack>
                    )}

                    {settings.contact_phone && (
                      <HStack align="start">
                        <Icon as={FiPhone} boxSize={5} color="blue.500" mt={1} />
                        <VStack align="start" spacing={0}>
                          <Text fontWeight="bold">Telefon</Text>
                          <Link href={`tel:${settings.contact_phone}`} color="blue.500">
                            {settings.contact_phone}
                          </Link>
                        </VStack>
                      </HStack>
                    )}

                    {settings.contact_email && (
                      <HStack align="start">
                        <Icon as={FiMail} boxSize={5} color="blue.500" mt={1} />
                        <VStack align="start" spacing={0}>
                          <Text fontWeight="bold">Email</Text>
                          <Link href={`mailto:${settings.contact_email}`} color="blue.500">
                            {settings.contact_email}
                          </Link>
                        </VStack>
                      </HStack>
                    )}
                  </VStack>
                </Box>
              )}
            </SimpleGrid>
          )}

          {/* Contacts by Category */}
          {hasContacts && (
            <Box>
              <Divider my={8} />
              
              <Accordion allowMultiple defaultIndex={[0]}>
                {Object.entries(contactsData.categories).map(([categoryName, contacts]) => (
                  <AccordionItem key={categoryName} border="none" mb={4}>
                    <AccordionButton
                      bg={bgColor}
                      borderRadius="lg"
                      p={4}
                      _hover={{ bg: useColorModeValue('gray.100', 'gray.700') }}
                      boxShadow="sm"
                    >
                      <Box flex="1" textAlign="left">
                        <Heading size="md">{categoryName}</Heading>
                        <Text fontSize="sm" color="gray.600">
                          {contacts.length} {contacts.length === 1 ? 'kontakt' : 'kontaktů'}
                        </Text>
                      </Box>
                      <AccordionIcon />
                    </AccordionButton>
                    <AccordionPanel pb={4} pt={4}>
                      <SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} spacing={6}>
                        {contacts.map((contact) => (
                          <Box
                            key={contact.id}
                            bg={bgColor}
                            p={6}
                            borderRadius="lg"
                            boxShadow="md"
                            border="1px"
                            borderColor={borderColor}
                            transition="transform 0.2s"
                            _hover={{ transform: 'translateY(-4px)', boxShadow: 'lg' }}
                          >
                            <VStack spacing={4} align="start">
                              {contact.image_url && (
                                <Avatar
                                  src={getImageUrl(contact.image_url)}
                                  name={contact.name}
                                  size="xl"
                                  alignSelf="center"
                                />
                              )}
                              <Box textAlign={contact.image_url ? 'center' : 'left'} w="100%">
                                <Heading size="sm" mb={1}>
                                  {contact.name}
                                </Heading>
                                {contact.position && (
                                  <Badge colorScheme="blue" mb={2}>
                                    {contact.position}
                                  </Badge>
                                )}
                              </Box>
                              {contact.description && (
                                <Text fontSize="sm" color="gray.600">
                                  {contact.description}
                                </Text>
                              )}
                              <VStack align="start" spacing={2} w="100%">
                                {contact.email && (
                                  <HStack spacing={2}>
                                    <Icon as={FiMail} color="blue.500" />
                                    <Link href={`mailto:${contact.email}`} fontSize="sm" color="blue.500">
                                      {contact.email}
                                    </Link>
                                  </HStack>
                                )}
                                {contact.phone && (
                                  <HStack spacing={2}>
                                    <Icon as={FiPhone} color="blue.500" />
                                    <Link href={`tel:${contact.phone}`} fontSize="sm" color="blue.500">
                                      {contact.phone}
                                    </Link>
                                  </HStack>
                                )}
                              </VStack>
                            </VStack>
                          </Box>
                        ))}
                      </SimpleGrid>
                    </AccordionPanel>
                  </AccordionItem>
                ))}

                {/* Uncategorized contacts */}
                {contactsData.uncategorized.length > 0 && (
                  <AccordionItem border="none" mb={4}>
                    <AccordionButton
                      bg={bgColor}
                      borderRadius="lg"
                      p={4}
                      _hover={{ bg: useColorModeValue('gray.100', 'gray.700') }}
                      boxShadow="sm"
                    >
                      <Box flex="1" textAlign="left">
                        <Heading size="md">Ostatní kontakty</Heading>
                        <Text fontSize="sm" color="gray.600">
                          {contactsData.uncategorized.length} {contactsData.uncategorized.length === 1 ? 'kontakt' : 'kontaktů'}
                        </Text>
                      </Box>
                      <AccordionIcon />
                    </AccordionButton>
                    <AccordionPanel pb={4} pt={4}>
                      <SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} spacing={6}>
                        {contactsData.uncategorized.map((contact) => (
                          <Box
                            key={contact.id}
                            bg={bgColor}
                            p={6}
                            borderRadius="lg"
                            boxShadow="md"
                            border="1px"
                            borderColor={borderColor}
                            transition="transform 0.2s"
                            _hover={{ transform: 'translateY(-4px)', boxShadow: 'lg' }}
                          >
                            <VStack spacing={4} align="start">
                              {contact.image_url && (
                                <Avatar
                                  src={getImageUrl(contact.image_url)}
                                  name={contact.name}
                                  size="xl"
                                  alignSelf="center"
                                />
                              )}
                              <Box textAlign={contact.image_url ? 'center' : 'left'} w="100%">
                                <Heading size="sm" mb={1}>
                                  {contact.name}
                                </Heading>
                                {contact.position && (
                                  <Badge colorScheme="blue" mb={2}>
                                    {contact.position}
                                  </Badge>
                                )}
                              </Box>
                              {contact.description && (
                                <Text fontSize="sm" color="gray.600">
                                  {contact.description}
                                </Text>
                              )}
                              <VStack align="start" spacing={2} w="100%">
                                {contact.email && (
                                  <HStack spacing={2}>
                                    <Icon as={FiMail} color="blue.500" />
                                    <Link href={`mailto:${contact.email}`} fontSize="sm" color="blue.500">
                                      {contact.email}
                                    </Link>
                                  </HStack>
                                )}
                                {contact.phone && (
                                  <HStack spacing={2}>
                                    <Icon as={FiPhone} color="blue.500" />
                                    <Link href={`tel:${contact.phone}`} fontSize="sm" color="blue.500">
                                      {contact.phone}
                                    </Link>
                                  </HStack>
                                )}
                              </VStack>
                            </VStack>
                          </Box>
                        ))}
                      </SimpleGrid>
                    </AccordionPanel>
                  </AccordionItem>
                )}
              </Accordion>
            </Box>
          )}
        </VStack>
      </Container>
    </Box>
  );
};

export default ContactsSection;
