import { Box, Text, VStack, HStack, Image, Skeleton, Link, SimpleGrid, Tooltip, Icon } from '@chakra-ui/react';
import { FaHandshake, FaExternalLinkAlt } from 'react-icons/fa';
import { Link as RouterLink } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { api } from '../../services/api';
import { Widget } from './Widget';
import { Sponsor } from '../../types';
import { assetUrl } from '../../utils/url';

export const SponsorsWidget = () => {
  const { data: sponsors = [], isLoading, error } = useQuery<Sponsor[]>({
    queryKey: ['sponsors'],
    queryFn: async () => {
      try {
        const { data } = await api.get('/sponsors');
        const raw = Array.isArray(data) ? data : (data?.data || []);
        // Normalize fields and resolve logo URL against backend origin
        return (raw || []).map((s: any) => ({
          ...s,
          logoUrl: assetUrl(s.logo_url) || s.logo_url,
          websiteUrl: s.website_url,
        }));
      } catch (err) {
        console.error('Error fetching sponsors:', err);
        return [];
      }
    },
    staleTime: 15 * 60 * 1000, // 15 minutes
  });

  if (isLoading) {
    return (
      <Widget title="Partneři klubu" icon={FaHandshake}>
        <SimpleGrid columns={2} spacing={4}>
          {[1, 2, 3, 4].map((i) => (
            <Skeleton key={i} height="80px" borderRadius="md" />
          ))}
        </SimpleGrid>
      </Widget>
    );
  }

  if (error || !sponsors.length) {
    return (
      <Widget title="Partneři klubu" icon={FaHandshake}>
        <VStack p={4} spacing={4}>
          <Box p={4} bg="gray.50" borderRadius="md" textAlign="center" w="full">
            <Icon as={FaHandshake} boxSize={6} color="gray.400" mb={2} />
            <Text color="gray.500">Žádní partneři k zobrazení</Text>
            <Text fontSize="sm" color="gray.400" mt={2}>
              Buďte první, kdo nás podpoří
            </Text>
          </Box>
        </VStack>
      </Widget>
    );
  }

  return (
    <Widget title="Partneři klubu" icon={FaHandshake}>
      <SimpleGrid columns={2} spacing={3}>
        {sponsors.map((sponsor) => (
          <Tooltip key={sponsor.id} label={sponsor.websiteUrl ? `Navštívit ${sponsor.name}` : sponsor.name} placement="top">
            <Link
              href={sponsor.websiteUrl || '#'}
              isExternal={!!sponsor.websiteUrl}
              _hover={{ textDecoration: 'none' }}
              display="block"
            >
              <Box
                p={3}
                borderWidth="1px"
                borderColor="gray.200"
                borderRadius="md"
                height="100%"
                display="flex"
                alignItems="center"
                justifyContent="center"
                bg="white"
                _hover={{ shadow: 'sm', borderColor: 'blue.200' }}
                transition="all 0.2s"
                position="relative"
                overflow="hidden"
              >
                {sponsor.websiteUrl && (
                  <Box
                    position="absolute"
                    top={1}
                    right={1}
                    color="blue.400"
                    fontSize="xs"
                    opacity={0.7}
                  >
                    <FaExternalLinkAlt />
                  </Box>
                )}
                <Image
                  src={sponsor.logoUrl || assetUrl((sponsor as any).logo_url) || '/images/sponsors/placeholder.png'}
                  alt={sponsor.name}
                  maxH="50px"
                  maxW="100px"
                  objectFit="contain"
                  fallback={
                    <Box
                      width="100px"
                      height="50px"
                      display="flex"
                      alignItems="center"
                      justifyContent="center"
                      bg="gray.50"
                      borderRadius="md"
                      p={2}
                      textAlign="center"
                    >
                      <Text fontSize="xs" color="gray.500" noOfLines={2}>
                        {sponsor.name}
                      </Text>
                    </Box>
                  }
                />
              </Box>
            </Link>
          </Tooltip>
        ))}
      </SimpleGrid>
      <Box mt={3} textAlign="center">
        <Link
          as={RouterLink}
          to="/partneri"
          fontSize="sm"
          color="blue.500"
          _hover={{ textDecoration: 'underline' }}
          display="inline-flex"
          alignItems="center"
          gap={1}
        >
          Zobrazit všechny partnery <FaExternalLinkAlt size={10} />
        </Link>
      </Box>
    </Widget>
  );
};

