import React, { useState, useEffect } from 'react';
import {
  Box,
  BoxProps,
  Container,
  Heading,
  Text,
  Skeleton,
  VStack,
  Image,
  HStack,
  Stack,
  Button,
  useColorModeValue,
} from '@chakra-ui/react';
import { Helmet } from 'react-helmet-async';
import api from '../services/api';
import DOMPurify from 'dompurify';
import { usePublicSettings } from '../hooks/usePublicSettings';
import MainLayout from '../components/layout/MainLayout';
import CompetitionMatches from '../components/home/CompetitionMatches';
import { getCategories, CategoryItem } from '../services/categories';
import { Link as RouterLink } from 'react-router-dom';
import SponsorsSection from '../components/common/SponsorsSection';
import NewsletterCTA from '../components/common/NewsletterCTA';

type AboutPageData = {
  title: string;
  subtitle: string;
  style: 'default' | 'modern' | 'timeline' | 'custom';
  content: string;
  seo_title: string;
  seo_description: string;
};

const AboutPage: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<AboutPageData | null>(null);
  const [error, setError] = useState<string>('');
  const { data: settings } = usePublicSettings();
  const [categories, setCategories] = useState<CategoryItem[]>([]);
  const cardBg = useColorModeValue('white', 'gray.800');
  const textSecondary = useColorModeValue('gray.600', 'gray.400');
  const borderSubtle = useColorModeValue('gray.100', 'gray.700');

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

  const loadData = async () => {
    setLoading(true);
    setError('');
    try {
      const res = await api.get('/about');
      setData(res.data);
    } catch (e: any) {
      if (e?.response?.status === 404) {
        setError('About page has not been created yet.');
      } else {
        setError('Nepodařilo se načíst stránku.');
      }
    } finally {
      setLoading(false);
    }
  };

  const loadCategories = async () => {
    try {
      const cats = await getCategories();
      setCategories(cats || []);
    } catch {}
  };

  // Make images inside HTML content responsive and lazy
  useEffect(() => {
    try {
      const containers = document.querySelectorAll('.about-content img, .about-timeline img');
      containers.forEach((img) => {
        if (img instanceof HTMLImageElement) {
          img.loading = 'lazy';
          img.decoding = 'async';
          img.style.maxWidth = '100%';
          img.style.height = 'auto';
          img.style.display = 'block';
        }
      });
    } catch {}
  }, [data]);

  if (loading) {
    return (
      <MainLayout>
        <Container maxW="container.lg" py={8}>
          <VStack align="stretch" spacing={4}>
            <Skeleton height="60px" />
            <Skeleton height="400px" />
          </VStack>
        </Container>
      </MainLayout>
    );
  }

  const renderCategoriesList = (marginTop: BoxProps['mt'] = 2) => {
    if (categories.length === 0) return null;
    return (
      <Box mt={marginTop}>
        <Heading as="h2" size="md" mb={4}>Rubriky</Heading>
        <VStack align="stretch" spacing={3}>
          {categories.map((c) => (
            <Stack
              key={c.id}
              direction={{ base: 'column', sm: 'row' }}
              spacing={{ base: 3, sm: 4 }}
              align={{ base: 'flex-start', sm: 'center' }}
              bg={cardBg}
              borderRadius="md"
              p={{ base: 4, md: 5 }}
              boxShadow="sm"
              borderWidth="1px"
              borderColor={borderSubtle}
              w="100%"
            >
              <Box flex="1" minW={0}>
                <Heading as="h3" size="sm" mb={c.description ? 1 : 0}>
                  {c.name}
                </Heading>
                {c.description && (
                  <Text fontSize="sm" color={textSecondary} noOfLines={{ base: 3, md: 2 }}>
                    {c.description}
                  </Text>
                )}
              </Box>
              <Button
                as={RouterLink}
                to={`/blog?category=${c.id}`}
                size="sm"
                variant="outline"
                colorScheme="blue"
                fontWeight="bold"
                w={{ base: 'full', sm: 'auto' }}
              >
                Otevřít
              </Button>
            </Stack>
          ))}
        </VStack>
      </Box>
    );
  };

  if (error || !data) {
    return (
      <MainLayout>
        <Helmet>
          <title>{settings?.club_name ? `O klubu | ${settings.club_name}` : 'O klubu'}</title>
          <meta name="description" content="Informace o našem klubu, soutěžích, nadcházejících zápasech a rubrikách." />
          {settings?.club_logo_url && <meta property="og:image" content={settings.club_logo_url} />}
        </Helmet>
        <Container maxW="container.lg" py={8}>
          <Box textAlign="center" py={6}>
            <Heading size="xl" mb={2}>O klubu</Heading>
            <Text color={textSecondary}>Tato stránka ještě není nastavena. Zde je přehled klubu, soutěží a rubrik.</Text>
          </Box>

          {/* Matches slider by competition (FACR) */}
          <Box mt={4} mb={10}>
            <Heading as="h2" size="md" mb={4}>Zápasy podle soutěží</Heading>
            <CompetitionMatches />
          </Box>
          {renderCategoriesList()}
        </Container>
      </MainLayout>
    );
  }

  const seoTitle = data.seo_title || data.title;
  const seoDesc = data.seo_description || data.subtitle;
  const clubName = settings?.club_name || data.title;
  const clubLogo = settings?.club_logo_url;
  const cleanContent = DOMPurify.sanitize(data.content);

  const renderContent = () => {
    switch (data.style) {
      case 'modern':
        return (
          <Box>
            {/* Header with club logo and name */}
            <HStack spacing={4} mb={8} align="center">
              {clubLogo && (
                <Image src={clubLogo} alt={clubName} boxSize="64px" objectFit="contain" />
              )}
              <VStack align="start" spacing={1}>
                <Heading size="2xl">{clubName}</Heading>
                {data.subtitle && (
                  <Text fontSize="xl" color={textSecondary}>
                    {data.subtitle}
                  </Text>
                )}
              </VStack>
            </HStack>

            {/* Content */}
            <Box
              className="about-content"
              dangerouslySetInnerHTML={{ __html: cleanContent }}
              sx={{
                '& p': { mb: 4, lineHeight: 1.8 },
                '& h1, & h2, & h3': { mt: 8, mb: 4, fontWeight: 'bold' },
                '& h1': { fontSize: '2xl' },
                '& h2': { fontSize: 'xl' },
                '& h3': { fontSize: 'lg' },
                '& img': { maxW: '100%', borderRadius: 'md', my: 6 },
                '& ul, & ol': { pl: 6, mb: 4 },
                '& li': { mb: 2 },
              }}
            />
          </Box>
        );

      case 'timeline':
        return (
          <Box>
            {/* Header with club logo and name */}
            <HStack spacing={4} mb={8} align="center">
              {clubLogo && (
                <Image src={clubLogo} alt={clubName} boxSize="64px" objectFit="contain" />
              )}
              <VStack align="start" spacing={1}>
                <Heading size="2xl">{clubName}</Heading>
                {data.subtitle && (
                  <Text fontSize="xl" color={textSecondary}>
                    {data.subtitle}
                  </Text>
                )}
              </VStack>
            </HStack>

            {/* Timeline Content */}
            <Box
              className="about-timeline"
              dangerouslySetInnerHTML={{ __html: cleanContent }}
              sx={{
                position: 'relative',
                '&::before': {
                  content: '""',
                  position: 'absolute',
                  left: '20px',
                  top: 0,
                  bottom: 0,
                  width: '2px',
                  bg: 'gray.300',
                },
                '& p': { mb: 4, lineHeight: 1.8, pl: 12, position: 'relative' },
                '& h1, & h2, & h3': {
                  mt: 8,
                  mb: 4,
                  fontWeight: 'bold',
                  pl: 12,
                  position: 'relative',
                  '&::before': {
                    content: '""',
                    position: 'absolute',
                    left: '11px',
                    top: '8px',
                    width: '20px',
                    height: '20px',
                    borderRadius: 'full',
                    bg: 'brand.500',
                    border: '4px solid white',
                    boxShadow: 'md',
                  },
                },
                '& img': { maxW: '100%', borderRadius: 'md', my: 6, ml: 12 },
              }}
            />
          </Box>
        );

      case 'custom':
        // Full custom HTML - just render as-is with minimal styling
        return (
          <Box dangerouslySetInnerHTML={{ __html: cleanContent }} />
        );

      case 'default':
      default:
        return (
          <Box>
            <HStack spacing={4} mb={8} align="center">
              {clubLogo && (
                <Image src={clubLogo} alt={clubName} boxSize="64px" objectFit="contain" />
              )}
              <VStack align="start" spacing={1}>
                <Heading size="2xl">{clubName}</Heading>
                {data.subtitle && (
                  <Text fontSize="xl" color={textSecondary}>
                    {data.subtitle}
                  </Text>
                )}
              </VStack>
            </HStack>

            <Box
              className="about-content"
              dangerouslySetInnerHTML={{ __html: cleanContent }}
              sx={{
                '& p': { mb: 4, lineHeight: 1.8 },
                '& h1, & h2, & h3': { mt: 6, mb: 3, fontWeight: 'bold' },
                '& h1': { fontSize: '2xl' },
                '& h2': { fontSize: 'xl' },
                '& h3': { fontSize: 'lg' },
                '& img': { maxW: '100%', borderRadius: 'md', my: 4 },
                '& ul, & ol': { pl: 6, mb: 4 },
                '& li': { mb: 2 },
              }}
            />
          </Box>
        );
    }
  };

  return (
    <MainLayout>
      <Helmet>
        <title>{seoTitle || clubName}</title>
        <meta name="description" content={seoDesc || `Informace o našem klubu, soutěžích, nadcházejících zápasech a rubrikách.`} />
        <meta property="og:title" content={seoTitle || clubName} />
        <meta property="og:description" content={seoDesc || `Informace o našem klubu, soutěžích, nadcházejících zápasech a rubrikách.`} />
        {clubLogo && <meta property="og:image" content={clubLogo} />}
      </Helmet>
      <Container maxW="container.lg" py={8}>
        {renderContent()}
        {renderCategoriesList({ base: 10, md: 12 })}
      </Container>

      {/* Newsletter CTA */}
      <NewsletterCTA />

      {/* Sponsors Section */}
      <SponsorsSection />
    </MainLayout>
  );
};

export default AboutPage;
