import React, { useEffect, useState } from 'react';
import { Link as RouterLink } from 'react-router-dom';
import {
  Box,
  Container,
  Heading,
  SimpleGrid,
  Image,
  Text,
  VStack,
  HStack,
  Badge,
  Spinner,
  Button,
  useColorModeValue,
} from '@chakra-ui/react';
import { Calendar, Image as ImageIcon, ExternalLink } from 'lucide-react';
import MainLayout from '../components/layout/MainLayout';
import SponsorsSection from '../components/common/SponsorsSection';
import NewsletterCTA from '../components/common/NewsletterCTA';

interface Album {
  id: string;
  title: string;
  url: string;
  date: string;
  photos_count: number;
  views_count?: number;
  photos: Array<{
    id: string;
    page_url: string;
    image_1500: string;
  }>;
  fetched_at?: string;
}

const resolveBackendUrl = (path: string) => {
  try {
    if (/^https?:\/\//i.test(path)) return path;
    if (path.startsWith('/cache') || path.startsWith('/uploads') || path.startsWith('/api/')) {
      const base = (process.env.REACT_APP_API_BASE_URL || process.env.REACT_APP_API_URL || 'http://localhost:8080/api/v1');
      const b = new URL(base);
      const abs = new URL(path, `${b.protocol}//${b.host}`);
      return abs.toString();
    }
    return path;
  } catch {
    return path;
  }
};

const GalleryPage: React.FC = () => {
  const [albums, setAlbums] = useState<Album[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>('');
  const [zoneramaProfileUrl, setZoneramaProfileUrl] = useState<string>('https://zonerama.com');
  const bgApp = useColorModeValue('#f8f9fb', '#0f1115');
  const cardBg = useColorModeValue('white', '#1a1d29');
  const borderColor = useColorModeValue('#e5e7eb', '#2a2e3a');
  const textPrimary = useColorModeValue('gray.800', 'gray.100');
  const textSecondary = useColorModeValue('gray.600', 'gray.300');
  const infoBg = useColorModeValue('blue.50', 'blue.900');
  const infoBorder = useColorModeValue('blue.200', 'blue.700');
  const infoText = useColorModeValue('blue.800', 'blue.200');
  const errorBg = useColorModeValue('red.50', 'red.900');
  const errorBorder = useColorModeValue('red.200', 'red.700');
  const errorText = useColorModeValue('red.600', 'red.300');

  useEffect(() => {
    const fetchAlbums = async () => {
      setLoading(true);
      setError('');
      
      try {
        // Load from both sources and combine
        const [profileRes, albumsRes] = await Promise.allSettled([
          fetch(resolveBackendUrl('/cache/prefetch/zonerama_profile.json'), { cache: 'no-cache' }),
          fetch(resolveBackendUrl('/cache/prefetch/zonerama_albums.json'), { cache: 'no-cache' })
        ]);
        
        let combinedAlbums: Album[] = [];
        
        // Get profile albums (newest/main source)
        if (profileRes.status === 'fulfilled' && profileRes.value.ok) {
          const profileData = await profileRes.value.json();
          combinedAlbums = [...(profileData.albums || [])];
          
          // Extract Zonerama profile URL
          if (profileData.input_link) {
            setZoneramaProfileUrl(profileData.input_link);
          }
        }
        
        // Get blog-related albums (additional source)
        if (albumsRes.status === 'fulfilled' && albumsRes.value.ok) {
          const albumsData = await albumsRes.value.json();
          const blogAlbums = Array.isArray(albumsData) ? albumsData : [];
          
          // Filter out albums with empty/invalid data and avoid duplicates
          const validBlogAlbums = blogAlbums.filter((album: any) => 
            album.id && 
            album.title && 
            !combinedAlbums.some(existing => existing.id === album.id)
          );
          
          combinedAlbums = [...combinedAlbums, ...validBlogAlbums];
        }
        
        // Sort by date (newest first) - parse Czech date format "DD. MM. YYYY"
        combinedAlbums.sort((a, b) => {
          const parseDate = (dateStr: string) => {
            if (!dateStr) return new Date(0);
            const parts = dateStr.split(/[.\s]+/).filter(Boolean);
            if (parts.length === 3) {
              const [day, month, year] = parts;
              return new Date(`${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`);
            }
            return new Date(dateStr);
          };
          
          return parseDate(b.date).getTime() - parseDate(a.date).getTime();
        });
        
        setAlbums(combinedAlbums);
      } catch (err: any) {
        setError(err.message || 'Nepodařilo se načíst alba');
      } finally {
        setLoading(false);
      }
    };

    fetchAlbums();
  }, []);

  return (
    <MainLayout>
      <Box bg={bgApp} minH="100vh" py={8}>
        <Container maxW="7xl">
          {/* Header */}
          <VStack align="stretch" spacing={6} mb={8}>
            <Heading size="2xl" color={textPrimary}>
              Fotogalerie
            </Heading>
            
            {/* Zonerama Attribution */}
            <Box
              bg={infoBg}
              borderWidth="1px"
              borderColor={infoBorder}
              borderRadius="md"
              p={4}
            >
              <Text fontSize="sm" color={infoText}>
                📸 Všechny fotografie jsou z platformy{' '}
                <Text
                  as="a"
                  href="https://zonerama.com"
                  target="_blank"
                  rel="noopener noreferrer"
                  fontWeight="600"
                  color="blue.600"
                  _hover={{ textDecoration: 'underline' }}
                >
                  Zonerama
                </Text>
              </Text>
            </Box>
          </VStack>

          {/* Loading State */}
          {loading && (
            <VStack spacing={4} py={12}>
              <Spinner size="xl" color="brand.primary" />
              <Text color={textSecondary}>Načítám alba...</Text>
            </VStack>
          )}

          {/* Error State */}
          {error && !loading && (
            <Box
              bg={errorBg}
              borderWidth="1px"
              borderColor={errorBorder}
              borderRadius="md"
              p={4}
              textAlign="center"
            >
              <Text color={errorText}>{error}</Text>
            </Box>
          )}

          {/* Empty State */}
          {!loading && !error && albums.length === 0 && (
            <Box
              bg={cardBg}
              borderWidth="1px"
              borderColor={borderColor}
              borderRadius="lg"
              p={12}
              textAlign="center"
            >
              <VStack spacing={4}>
                <ImageIcon size={48} color="gray" />
                <Heading size="md" color={textSecondary}>
                  Zatím nejsou k dispozici žádná alba
                </Heading>
                <Text color={textSecondary}>
                  Alba se zde zobrazí po jejich načtení ze Zonerama.
                </Text>
              </VStack>
            </Box>
          )}

          {/* Albums Grid */}
          {!loading && !error && albums.length > 0 && (
            <>
              <SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} spacing={6}>
                {albums.map((album) => {
                  // Get the first photo as cover image
                  const coverPhoto = album.photos && album.photos.length > 0 
                    ? album.photos[0] 
                    : null;

                  return (
                    <Box
                      key={album.id}
                      as={RouterLink}
                      to={`/galerie/album/${album.id}`}
                      bg={cardBg}
                      borderRadius="lg"
                      overflow="hidden"
                      boxShadow="md"
                      borderWidth="1px"
                      borderColor={borderColor}
                      transition="all 0.2s"
                      _hover={{
                        transform: 'translateY(-4px)',
                        boxShadow: 'xl',
                        borderColor: useColorModeValue('gray.300', 'gray.600'),
                      }}
                      cursor="pointer"
                    >
                      {/* Cover Image */}
                      {coverPhoto ? (
                        <Image
                          src={resolveBackendUrl(coverPhoto.image_1500)}
                          alt={album.title}
                          w="100%"
                          h="250px"
                          objectFit="cover"
                          loading="lazy"
                        />
                      ) : (
                        <Box
                          w="100%"
                          h="250px"
                          bg="gray.200"
                          display="flex"
                          alignItems="center"
                          justifyContent="center"
                        >
                          <ImageIcon size={48} color="gray" />
                        </Box>
                      )}

                      {/* Album Info */}
                      <VStack align="stretch" p={4} spacing={3}>
                        <Heading size="md" color={textPrimary} noOfLines={2}>
                          {album.title}
                        </Heading>
                        
                        <HStack spacing={4} flexWrap="wrap" fontSize="sm" color={textSecondary}>
                          {album.date && (
                            <HStack spacing={1}>
                              <Calendar size={16} />
                              <Text>{album.date}</Text>
                            </HStack>
                          )}
                          <HStack spacing={1}>
                            <ImageIcon size={16} />
                            <Text>{album.photos_count} foto</Text>
                          </HStack>
                        </HStack>

                        {album.views_count !== undefined && album.views_count > 0 && (
                          <HStack>
                            <Badge colorScheme="purple" fontSize="xs">
                              {album.views_count} zhlédnutí
                            </Badge>
                          </HStack>
                        )}
                      </VStack>
                    </Box>
                  );
                })}
              </SimpleGrid>

              {/* Show More Button - Link to Zonerama Profile */}
              <Box textAlign="center" mt={8}>
                <Button
                  as="a"
                  href={zoneramaProfileUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  rightIcon={<ExternalLink size={18} />}
                  colorScheme="blue"
                  size="lg"
                  variant="outline"
                >
                  Zobrazit další alba na Zonerama
                </Button>
              </Box>
            </>
          )}
        </Container>
      </Box>
      
      {/* Newsletter CTA */}
      <NewsletterCTA />
      
      {/* Sponsors Section */}
      <SponsorsSection />
    </MainLayout>
  );
};

export default GalleryPage;
