import { Box, Button, FormControl, FormErrorMessage, FormLabel, Heading, Image, Input, Link, SimpleGrid, Spinner, Stack, Text, Textarea, VStack, useToast, Grid, GridItem, useColorModeValue } from '@chakra-ui/react';
import { useQuery, useMutation } from '@tanstack/react-query';
import { getSponsors, sendContact } from '../services/public';
import MainLayout from '../components/layout/MainLayout';
import { useForm } from 'react-hook-form';

type ContactFormData = { name: string; email: string; subject: string; message: string; source?: string };

const SponsorsPage: React.FC = () => {
  const { data, isLoading, isError, error } = useQuery({ queryKey: ['sponsors-page'], queryFn: getSponsors });
  const toast = useToast();
  const cardBg = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.700');
  const formBg = useColorModeValue('gray.50', 'gray.900');
  const textSecondary = useColorModeValue('gray.600', 'gray.400');
  const textTertiary = useColorModeValue('gray.700', 'gray.300');

  const { register, handleSubmit, reset, formState: { errors } } = useForm<ContactFormData>();
  const { mutate, isLoading: sending } = useMutation({
    mutationFn: (payload: ContactFormData) => sendContact({ ...payload, source: 'sponsor' }),
    onSuccess: () => {
      reset();
      toast({ title: 'Zpráva odeslána', description: 'Děkujeme za zprávu.', status: 'success' });
    },
    onError: (e:any) => {
      const code = e?.code || '';
      const fromServer = e?.response?.data?.error || e?.response?.data?.message;
      const isTimeout = code === 'ECONNABORTED' || /timeout/i.test(String(e?.message || ''));
      const isNetwork = !!e?.isAxiosError && !e?.response;
      const msg = fromServer
        || (isTimeout ? 'Vypršel časový limit požadavku. Zkuste to prosím znovu.'
            : isNetwork ? 'Požadavek se nezdařil (síť/CORS). Obnovte stránku a zkuste znovu.'
            : (e?.message || 'Odeslání se nezdařilo'));
      toast({ title: 'Chyba', description: msg, status: 'error' });
    }
  });

  if (isLoading) return <Spinner />;
  if (isError) {
    const errMsg = (error as any)?.response?.data?.error || (error as any)?.message || 'Chyba při načítání sponzorů';
    return <Text color="red.500">{errMsg}</Text>;
  }

  // Group sponsors by tier
  const generalPartners = data?.filter((s) => s.tier === 'general') || [];
  const standardSponsors = data?.filter((s) => s.tier !== 'general') || [];

  return (
    <MainLayout>
      <VStack align="stretch" spacing={10} maxW="7xl" mx="auto" px={{ base: 4, md: 6 }} py={{ base: 6, md: 10 }}>
        {/* Main sponsors section */}
        <Box>
          <Heading size="lg" mb={6}>Naši partneři</Heading>
          
          {/* General Partners - Larger display */}
          {generalPartners.length > 0 && (
            <Box mb={8}>
              <Heading size="md" mb={4} color="brand.600">Hlavní partneři</Heading>
              <SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} spacing={8}>
                {generalPartners.map((s) => (
                  <Stack key={s.id} align="center" bg={cardBg} p={6} borderRadius="lg" borderWidth="2px" borderColor={borderColor} boxShadow="md">
                    <Link href={s.website_url || '#'} isExternal>
                      <Image src={s.logo_url || '/logo192.png'} alt={s.name} height="100px" objectFit="contain" />
                    </Link>
                    <Text fontWeight="semibold" fontSize="lg">{s.name}</Text>
                  </Stack>
                ))}
              </SimpleGrid>
            </Box>
          )}

          {/* Standard Sponsors - Regular display */}
          {standardSponsors.length > 0 && (
            <Box>
              <Heading size="md" mb={4} color={textTertiary}>Partneři</Heading>
              <SimpleGrid columns={{ base: 2, md: 3, lg: 5 }} spacing={6}>
                {standardSponsors.map((s) => (
                  <Stack key={s.id} align="center" bg={cardBg} p={4} borderRadius="md" borderWidth="1px" borderColor={borderColor}>
                    <Link href={s.website_url || '#'} isExternal>
                      <Image src={s.logo_url || '/logo192.png'} alt={s.name} height="60px" objectFit="contain" />
                    </Link>
                    <Text fontSize="sm">{s.name}</Text>
                  </Stack>
                ))}
              </SimpleGrid>
            </Box>
          )}
        </Box>

        {/* Compact contact form on the side/bottom */}
        <Box bg={formBg} p={6} borderRadius="lg" borderWidth="1px" borderColor={borderColor} maxW="600px" mx="auto" w="full">
          <Heading size="sm" mb={3}>Staňte se partnerem</Heading>
          <Text fontSize="sm" color={textSecondary} mb={4}>Máte zájem o spolupráci? Kontaktujte nás.</Text>
          <form onSubmit={handleSubmit((vals)=>mutate({ ...vals }))}>
            <VStack spacing={3}>
              <FormControl isInvalid={!!errors.name} size="sm">
                <FormLabel fontSize="sm">Jméno</FormLabel>
                <Input size="sm" {...register('name', { required: 'Vyplňte prosím jméno' })} placeholder="Jan Novák" />
                <FormErrorMessage fontSize="xs">{errors.name?.message}</FormErrorMessage>
              </FormControl>
              <FormControl isInvalid={!!errors.email} size="sm">
                <FormLabel fontSize="sm">E‑mail</FormLabel>
                <Input size="sm" type="email" {...register('email', { required: 'Vyplňte prosím e‑mail' })} placeholder="vas@email.cz" />
                <FormErrorMessage fontSize="xs">{errors.email?.message}</FormErrorMessage>
              </FormControl>
              <FormControl size="sm">
                <FormLabel fontSize="sm">Předmět</FormLabel>
                <Input size="sm" {...register('subject', { required: 'Předmět je povinný' })} placeholder="Partnerství" />
                <FormErrorMessage fontSize="xs">{errors.subject?.message}</FormErrorMessage>
              </FormControl>
              <FormControl isInvalid={!!errors.message} size="sm">
                <FormLabel fontSize="sm">Zpráva</FormLabel>
                <Textarea size="sm" rows={3} {...register('message', { required: 'Napište prosím krátkou zprávu' })} placeholder="Rádi bychom navázali spolupráci..." />
                <FormErrorMessage fontSize="xs">{errors.message?.message}</FormErrorMessage>
              </FormControl>
              <Button type="submit" size="sm" colorScheme="brand" isLoading={sending} w="full">Odeslat</Button>
            </VStack>
          </form>
        </Box>
      </VStack>
    </MainLayout>
  );
}

export default SponsorsPage;
