import React, { useState } from 'react';
import {
  Box,
  Button,
  VStack,
  HStack,
  Input,
  Text,
  SimpleGrid,
  Image,
  Checkbox,
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalFooter,
  ModalCloseButton,
  useToast,
  Spinner,
  Badge,
  FormControl,
  FormLabel,
  FormHelperText,
} from '@chakra-ui/react';
import { ExternalLink, Download } from 'lucide-react';
import { getZoneramaAlbum } from '../../services/zonerama';

interface Photo {
  id: string;
  page_url: string;
  image_1500: string;
}

interface Album {
  id: string;
  title: string;
  url: string;
  date: string;
  photos_count: number;
  photos: Photo[];
}

interface AlbumPhotoPickerProps {
  isOpen: boolean;
  onClose: () => void;
  onPhotosSelected: (photos: Photo[], albumInfo: Album) => void;
}

const AlbumPhotoPicker: React.FC<AlbumPhotoPickerProps> = ({
  isOpen,
  onClose,
  onPhotosSelected,
}) => {
  const [albumLink, setAlbumLink] = useState('');
  const [loading, setLoading] = useState(false);
  const [album, setAlbum] = useState<Album | null>(null);
  const [selectedPhotos, setSelectedPhotos] = useState<Set<string>>(new Set());
  const toast = useToast();

  const handleFetchAlbum = async () => {
    if (!albumLink.trim()) {
      toast({
        title: 'Zadejte URL alba',
        status: 'warning',
        duration: 3000,
      });
      return;
    }

    if (!albumLink.includes('/Album/')) {
      toast({
        title: 'Neplatný odkaz',
        description: 'URL musí obsahovat "/Album/"',
        status: 'error',
        duration: 3000,
      });
      return;
    }

    setLoading(true);
    try {
      const result = await getZoneramaAlbum(albumLink, { photo_limit: 100 }) as any;
      
      // Handle both response formats: { album, photos } and { albums: [{ photos }] }
      let albumData: any = null;
      let photos: any[] = [];
      
      if (result.albums && Array.isArray(result.albums) && result.albums.length > 0) {
        // New format: { albums: [{ id, title, url, date, photos }] }
        albumData = result.albums[0];
        photos = albumData.photos || [];
      } else if (result.album && result.photos) {
        // Old format: { album: {...}, photos: [...] }
        albumData = result.album;
        photos = result.photos;
      } else {
        throw new Error('Album nenalezeno - neplatná odpověď ze serveru');
      }
      
      if (!albumData) {
        throw new Error('Album nenalezeno');
      }
      
      const mappedPhotos = photos.map(p => ({
        id: p.id,
        page_url: p.page_url,
        image_1500: p.image_1500 || '',
      }));
      
      setAlbum({
        id: albumData.id || '',
        title: albumData.title || '',
        url: albumData.url || albumLink,
        date: albumData.date || '', // Now properly extracting date
        photos_count: mappedPhotos.length,
        photos: mappedPhotos,
      });
      setSelectedPhotos(new Set());
      
      toast({
        title: 'Album načteno',
        description: `${mappedPhotos.length} fotografií`,
        status: 'success',
        duration: 2000,
      });
    } catch (error: any) {
      console.error('Album fetch error:', error);
      toast({
        title: 'Chyba načítání alba',
        description: error.message || 'Nepodařilo se načíst album',
        status: 'error',
        duration: 5000,
      });
    } finally {
      setLoading(false);
    }
  };

  const togglePhoto = (photoId: string) => {
    const newSelected = new Set(selectedPhotos);
    if (newSelected.has(photoId)) {
      newSelected.delete(photoId);
    } else {
      newSelected.add(photoId);
    }
    setSelectedPhotos(newSelected);
  };

  const handleSelectAll = () => {
    if (album) {
      if (selectedPhotos.size === album.photos.length) {
        setSelectedPhotos(new Set());
      } else {
        setSelectedPhotos(new Set(album.photos.map(p => p.id)));
      }
    }
  };

  const handleConfirm = () => {
    if (!album || selectedPhotos.size === 0) {
      toast({
        title: 'Vyberte fotografie',
        status: 'warning',
        duration: 3000,
      });
      return;
    }

    const selected = album.photos.filter(p => selectedPhotos.has(p.id));
    onPhotosSelected(selected, album);
    handleClose();
  };

  const handleClose = () => {
    setAlbumLink('');
    setAlbum(null);
    setSelectedPhotos(new Set());
    onClose();
  };

  return (
    <Modal isOpen={isOpen} onClose={handleClose} size="6xl">
      <ModalOverlay />
      <ModalContent maxH="90vh">
        <ModalHeader>Vybrat fotografie z alba</ModalHeader>
        <ModalCloseButton />
        <ModalBody overflowY="auto">
          <VStack align="stretch" spacing={4}>
            {/* Album URL Input */}
            <FormControl>
              <FormLabel>URL Zonerama alba</FormLabel>
              <HStack>
                <Input
                  value={albumLink}
                  onChange={(e) => setAlbumLink(e.target.value)}
                  placeholder="https://eu.zonerama.com/Account/Album/12345"
                  onKeyPress={(e) => e.key === 'Enter' && handleFetchAlbum()}
                />
                <Button
                  onClick={handleFetchAlbum}
                  isLoading={loading}
                  colorScheme="blue"
                  leftIcon={<Download size={18} />}
                >
                  Načíst
                </Button>
              </HStack>
              <FormHelperText>
                Vložte odkaz na Zonerama album (musí obsahovat /Album/)
              </FormHelperText>
            </FormControl>

            {/* Loading State */}
            {loading && (
              <VStack py={8}>
                <Spinner size="xl" color="blue.500" />
                <Text color="gray.600">Načítám album...</Text>
              </VStack>
            )}

            {/* Album Info & Photos */}
            {album && !loading && (
              <>
                {/* Album Header */}
                <Box
                  p={4}
                  bg="blue.50"
                  borderRadius="md"
                  borderWidth="1px"
                  borderColor="blue.200"
                >
                  <VStack align="start" spacing={2}>
                    <HStack justify="space-between" w="full">
                      <Text fontWeight="bold" fontSize="lg">
                        {album.title}
                      </Text>
                      <Button
                        as="a"
                        href={album.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        size="sm"
                        variant="ghost"
                        rightIcon={<ExternalLink size={14} />}
                      >
                        Zonerama
                      </Button>
                    </HStack>
                    <HStack spacing={4} fontSize="sm" color="gray.700">
                      {album.date && <Text>📅 {album.date}</Text>}
                      <Badge colorScheme="blue">{album.photos.length} fotografií</Badge>
                    </HStack>
                  </VStack>
                </Box>

                {/* Select All */}
                <HStack justify="space-between">
                  <Checkbox
                    isChecked={selectedPhotos.size === album.photos.length}
                    isIndeterminate={
                      selectedPhotos.size > 0 && selectedPhotos.size < album.photos.length
                    }
                    onChange={handleSelectAll}
                  >
                    Vybrat vše ({selectedPhotos.size}/{album.photos.length})
                  </Checkbox>
                </HStack>

                {/* Photos Grid */}
                <SimpleGrid columns={{ base: 3, md: 4, lg: 5 }} spacing={3}>
                  {album.photos.map((photo) => (
                    <Box
                      key={photo.id}
                      position="relative"
                      cursor="pointer"
                      onClick={() => togglePhoto(photo.id)}
                      borderRadius="md"
                      overflow="hidden"
                      borderWidth="2px"
                      borderColor={selectedPhotos.has(photo.id) ? 'blue.500' : 'transparent'}
                      transition="all 0.2s"
                      _hover={{ transform: 'scale(1.05)' }}
                    >
                      <Image
                        src={photo.image_1500}
                        alt={photo.id}
                        w="100%"
                        h="150px"
                        objectFit="cover"
                      />
                      <Checkbox
                        position="absolute"
                        top={2}
                        right={2}
                        isChecked={selectedPhotos.has(photo.id)}
                        pointerEvents="none"
                        bg="white"
                        borderRadius="sm"
                      />
                    </Box>
                  ))}
                </SimpleGrid>
              </>
            )}
          </VStack>
        </ModalBody>
        <ModalFooter>
          <HStack spacing={3}>
            <Button variant="ghost" onClick={handleClose}>
              Zrušit
            </Button>
            <Button
              colorScheme="blue"
              onClick={handleConfirm}
              isDisabled={!album || selectedPhotos.size === 0}
            >
              Vybrat ({selectedPhotos.size})
            </Button>
          </HStack>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
};

export default AlbumPhotoPicker;
