import React, { useState, useEffect, useCallback } from 'react';
import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalFooter,
  ModalCloseButton,
  Button,
  VStack,
  useToast,
  Text,
  Box,
  SimpleGrid,
  Image,
  Heading,
  Divider,
  Checkbox,
  HStack,
  Alert,
  AlertIcon,
  Progress,
  CircularProgress,
  Center,
  Stack,
  Grid,
  GridItem,
  Spinner,
  Tooltip,
  useColorModeValue,
  Badge,
  Fade,
  ScaleFade,
  Menu,
  MenuButton,
  MenuList,
  MenuItem,
  MenuDivider,
  IconButton,
  ButtonGroup,
  Flex
} from '@chakra-ui/react';
import { processImages } from './ImageProcessor';
import {
  InfoIcon,
  CheckIcon,
  WarningIcon,
  ViewIcon,
  EditIcon,
  SmallCloseIcon,
  ArrowForwardIcon,
  ChevronDownIcon,
  DeleteIcon,
  RepeatIcon,
  ChevronLeftIcon,
  ChevronRightIcon
} from '@chakra-ui/icons';

const ProductImagesModal = ({ isOpen, onClose, products, onImagesUpdated }) => {
  const [isProcessing, setIsProcessing] = useState(false);
  const [processedImages, setProcessedImages] = useState([]);
  const [selectedImages, setSelectedImages] = useState([]);
  const [currentProductIndex, setCurrentProductIndex] = useState(0);
  const [totalProgress, setTotalProgress] = useState(0);
  const [currentImageProgress, setCurrentImageProgress] = useState(0);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [error, setError] = useState(null);
  const [processingStage, setProcessingStage] = useState('');
  const [currentImageSize, setCurrentImageSize] = useState(null);
  const [processingStatus, setProcessingStatus] = useState('');
  const [isSaving, setIsSaving] = useState(false);
  const [saveProgress, setSaveProgress] = useState(0);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [selectAll, setSelectAll] = useState(false);
  const [viewMode, setViewMode] = useState('grid'); // 'grid' or 'list'
  const toast = useToast();

  // Move color mode hooks to component level
  const cardBg = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.600');
  const selectedBg = useColorModeValue('blue.50', 'blue.900');
  const modalBg = useColorModeValue('gray.50', 'gray.900');
  const headerBg = useColorModeValue('white', 'gray.800');
  const imageBg = useColorModeValue('gray.50', 'gray.900');

  // Reset state when modal opens
  useEffect(() => {
    if (isOpen) {
      setSelectedImages([]);
      setProcessedImages([]);
      setError(null);
      setTotalProgress(0);
      setCurrentImageProgress(0);
      setCurrentImageIndex(0);
      setCurrentProductIndex(0);
    }
  }, [isOpen, products]);

  // Get all available images from all products
  const getAllImages = useCallback(() => {
    const allImages = [];
    products.forEach(product => {
      if (product.main_image) {
        allImages.push({
          ...product.main_image,
          productId: product.id,
          productName: product.name,
          type: 'main'
        });
      }
      if (product.gallery_images) {
        product.gallery_images.forEach(image => {
          allImages.push({
            ...image,
            productId: product.id,
            productName: product.name,
            type: 'gallery'
          });
        });
      }
    });
    return allImages;
  }, [products]);

  const allImages = getAllImages();

  // Handle select all images
  const handleSelectAll = () => {
    setSelectAll(!selectAll);
    if (!selectAll) {
      setSelectedImages(allImages.map(img => ({
        imageId: img.id,
        productId: img.productId
      })));
    } else {
      setSelectedImages([]);
    }
  };

  // Handle individual image selection
  const handleImageSelect = (imageId, productId) => {
    setSelectedImages(prev => {
      const isSelected = prev.some(item => item.imageId === imageId && item.productId === productId);
      if (isSelected) {
        return prev.filter(item => !(item.imageId === imageId && item.productId === productId));
      } else {
        return [...prev, { imageId, productId }];
      }
    });
  };

  const handleProcessImages = async () => {
    if (selectedImages.length === 0) {
      toast({
        title: 'No images selected',
        description: 'Please select at least one image to process',
        status: 'warning',
        duration: 3000,
      });
      return;
    }

    // Get selected image objects
    const imagesToProcess = selectedImages.map(selected => {
      const image = allImages.find(img =>
        img.id === selected.imageId && img.productId === selected.productId
      );
      return image;
    }).filter(Boolean);

    setIsProcessing(true);
    setError(null);
    setTotalProgress(0);
    setCurrentImageProgress(0);
    setCurrentImageIndex(0);
    setProcessingStage('Initializing...');

    try {
      const results = await processImages(imagesToProcess, {
        onProgress: ({ total, current, currentImage, totalImages, stage, imageSize }) => {
          setTotalProgress(Math.round(total));
          setCurrentImageProgress(Math.round(current));
          setCurrentImageIndex(currentImage - 1);
          setProcessingStage(stage || 'Processing...');
          if (imageSize) {
            setCurrentImageSize(imageSize);
          }
        }
      });

      // Debug logging
      console.log('Processed images results:', results);

      setProcessedImages(results.map(result => ({
        ...result,
        url: result.processedUrl || result.originalUrl
      })));

      const reducedQualityImages = results.filter(img => img.quality === 'reduced');
      if (reducedQualityImages.length > 0) {
        toast({
          title: 'Processing Complete with Adjustments',
          description: `${reducedQualityImages.length} image(s) were compressed to meet size requirements.`,
          status: 'info',
          duration: 5000,
          isClosable: true,
        });
      } else {
        toast({
          title: 'Processing Complete',
          description: `Successfully processed ${results.length} images`,
          status: 'success',
          duration: 3000,
        });
      }
    } catch (error) {
      console.error('Processing error:', error);
      setError(error.message || 'Failed to process images');
      toast({
        title: 'Processing Error',
        description: error.message || 'Failed to process images',
        status: 'error',
        duration: 5000,
      });
    } finally {
      setIsProcessing(false);
      setCurrentImageIndex(0);
      setCurrentImageProgress(0);
      setTotalProgress(0);
      setProcessingStage('');
      setCurrentImageSize(null);
    }
  };

  const handleSave = async () => {
    if (processedImages.length === 0) {
      toast({
        title: 'No processed images',
        description: 'Please process some images first',
        status: 'warning',
        duration: 3000,
      });
      return;
    }

    try {
      setIsSaving(true);
      setSaveProgress(0);
      setUploadProgress(0);

      // Convert processed image blobs to FormData
      const formData = new FormData();
      processedImages.forEach((image, index) => {
        formData.append(`images[${index}]`, image.processedBlob, `processed-${image.id}.jpg`);
        formData.append(`original_ids[${index}]`, image.id);
        // Update progress for each image added to formData
        setSaveProgress(((index + 1) / processedImages.length) * 20); // First 20% is for preparing data
      });

      // Show preparing to upload message
      toast({
        title: 'Preparing to save images',
        description: 'Starting upload to server...',
        status: 'info',
        duration: 2000,
      });

      // Start progress simulation for upload phase
      let progress = 0;
      window.uploadProgressInterval = setInterval(() => {
        progress += 1;
        if (progress <= 60) { // Simulate progress up to 80% (20% prep + 60% upload)
          setUploadProgress(progress);
          setSaveProgress(20 + progress); // 20% from prep + current upload progress
        } else {
          clearInterval(window.uploadProgressInterval);
        }
      }, 100); // Update every 100ms

      // Save processed images to WordPress
      const response = await fetch('/wp-json/klcnn/v1/save-processed-images', {
        method: 'POST',
        body: formData,
        credentials: 'same-origin',
        headers: {
          'X-WP-Nonce': window.klcnnData.nonce
        }
      });

      // Clear the interval when upload is complete
      clearInterval(window.uploadProgressInterval);
      setSaveProgress(85); // Upload complete

      if (!response.ok) {
        let errorMessage = 'Failed to save processed images';
        try {
          const errorData = await response.json();
          errorMessage = errorData.message || errorMessage;
        } catch (e) {
          errorMessage = await response.text();
        }
        throw new Error(errorMessage);
      }

      const result = await response.json();
      setSaveProgress(95); // Processing complete

      if (onImagesUpdated) {
        onImagesUpdated(result.images);
      }

      // Simulate final processing
      setTimeout(() => {
        setSaveProgress(100);

        toast({
          title: 'Images Saved Successfully',
          description: `Successfully saved ${processedImages.length} processed images`,
          status: 'success',
          duration: 3000,
        });

        // Add a small delay before closing to show 100% completion
        setTimeout(() => {
          handleClose();
        }, 500);
      }, 500);

    } catch (error) {
      // Clear the interval in case of error
      if (window.uploadProgressInterval) {
        clearInterval(window.uploadProgressInterval);
      }
      console.error('Error saving images:', error);
      toast({
        title: 'Error Saving Images',
        description: error.message || 'Failed to save processed images',
        status: 'error',
        duration: 5000,
      });
    } finally {
      if (window.uploadProgressInterval) {
        clearInterval(window.uploadProgressInterval);
      }
      setIsSaving(false);
      setUploadProgress(0);
      setSaveProgress(0);
    }
  };

  const handleClose = () => {
    if (isProcessing) {
      const confirmed = window.confirm('Processing is in progress. Are you sure you want to cancel?');
      if (!confirmed) return;
    }
    setProcessedImages([]);
    setSelectedImages([]);
    setError(null);
    setTotalProgress(0);
    setCurrentImageProgress(0);
    setCurrentImageIndex(0);
    setCurrentProductIndex(0);
    onClose();
  };

  const hasImages = Boolean(
    (allImages.find(img => img.type === 'main')?.url) ||
    (allImages.filter(img => img.type === 'gallery').length > 0)
  );

  // Add navigation between products
  const handleNextProduct = () => {
    if (Array.isArray(products) && currentProductIndex < products.length - 1) {
      setCurrentProductIndex(prev => prev + 1);
      setSelectedImages([]);
      setProcessedImages([]);
    }
  };

  const handlePreviousProduct = () => {
    if (Array.isArray(products) && currentProductIndex > 0) {
      setCurrentProductIndex(prev => prev - 1);
      setSelectedImages([]);
      setProcessedImages([]);
    }
  };

  const renderProgressIndicator = () => {
    if (!isProcessing) return null;

    const currentImageNumber = currentImageIndex + 1;
    const totalSelectedImages = selectedImages.length;

    return (
      <Box
        position="fixed"
        top="50%"
        left="50%"
        transform="translate(-50%, -50%)"
        bg="white"
        p={6}
        borderRadius="lg"
        boxShadow="xl"
        zIndex={1500}
        minW="300px"
      >
        <Stack spacing={4} align="center">
          <CircularProgress
            value={currentImageProgress}
            size="120px"
            thickness="8px"
            color="blue.500"
          >
            <CircularProgress
              value={totalProgress}
              size="120px"
              thickness="8px"
              color="green.500"
              position="absolute"
              top="0"
              left="0"
              opacity={0.3}
            />
            <Box position="absolute" top="50%" left="50%" transform="translate(-50%, -50%)">
              <Text fontSize="xl" fontWeight="bold">
                {Math.round(currentImageProgress)}%
              </Text>
            </Box>
          </CircularProgress>

          <Stack spacing={1} textAlign="center">
            <Text fontWeight="bold" fontSize="lg">
              Processing Images
            </Text>
            <Text fontSize="md" color="gray.600">
              {processingStage}
            </Text>
            <Text fontWeight="bold">
              Image {currentImageNumber} of {totalSelectedImages}
            </Text>
            {currentImageSize && (
              <Text fontSize="sm" color="gray.600">
                Size: {(currentImageSize / 1024 / 1024).toFixed(2)}MB
              </Text>
            )}
            <Text fontSize="sm" color="gray.600">
              Overall Progress: {totalProgress}%
            </Text>
          </Stack>

          <Progress
            value={totalProgress}
            size="sm"
            width="100%"
            colorScheme="blue"
            borderRadius="full"
            isAnimated
            hasStripe
          />
        </Stack>
      </Box>
    );
  };

  const renderSavingProgressIndicator = () => {
    if (!isSaving) return null;

    // Calculate the current stage
    let stage = 'Preparing...';
    if (saveProgress < 20) {
      stage = 'Preparing images for upload...';
    } else if (saveProgress < 80) {
      stage = `Uploading to server... (${Math.round(uploadProgress)}%)`;
    } else if (saveProgress < 95) {
      stage = 'Processing on server...';
    } else if (saveProgress < 100) {
      stage = 'Finalizing changes...';
    } else {
      stage = 'Save complete!';
    }

    return (
      <Box
        position="fixed"
        top="50%"
        left="50%"
        transform="translate(-50%, -50%)"
        bg="white"
        p={6}
        borderRadius="lg"
        boxShadow="xl"
        zIndex={1500}
        minW="300px"
      >
        <Stack spacing={4} align="center">
          <CircularProgress
            value={saveProgress}
            size="120px"
            thickness="8px"
            color="green.500"
          >
            <Box position="absolute" top="50%" left="50%" transform="translate(-50%, -50%)">
              <Text fontSize="xl" fontWeight="bold">
                {Math.round(saveProgress)}%
              </Text>
            </Box>
          </CircularProgress>

          <Stack spacing={1} textAlign="center">
            <Text fontWeight="bold" fontSize="lg">
              Saving Images
            </Text>
            <Text fontSize="md" color="gray.600">
              {stage}
            </Text>
            <Text fontSize="sm" color="gray.500">
              Please don't close this window
            </Text>
          </Stack>

          <Progress
            value={saveProgress}
            size="sm"
            width="100%"
            colorScheme="green"
            borderRadius="full"
            isAnimated
            hasStripe
          />
        </Stack>
      </Box>
    );
  };

  const renderImageCard = (image) => {
    const isSelected = selectedImages.some(item =>
      item.imageId === image.id && item.productId === image.productId
    );
    const processedImage = processedImages.find(img => img.id === image.id);

    return (
      <ScaleFade in={true} initialScale={0.9}>
        <Box
          borderWidth="1px"
          borderRadius="xl"
          overflow="hidden"
          bg={isSelected ? selectedBg : cardBg}
          transition="all 0.2s"
          _hover={{
            transform: 'translateY(-2px)',
            shadow: 'lg',
            borderColor: 'blue.400'
          }}
          position="relative"
          borderColor={isSelected ? 'blue.400' : borderColor}
        >
          <Box position="relative" overflow="hidden">
            {processedImage ? (
              <HStack spacing={0} width="100%" height="200px">
                <Box position="relative" width="50%" height="100%" borderRightWidth="1px">
                  <Text fontSize="xs" color="gray.500" position="absolute" top={1} left={2}>Original</Text>
                  <Image
                    src={image.url}
                    alt={`Original ${image.type} image`}
                    width="100%"
                    height="100%"
                    objectFit="contain"
                    bg={imageBg}
                    p={2}
                  />
                </Box>
                <Box position="relative" width="50%" height="100%" bg="white">
                  <Text fontSize="xs" color="gray.500" position="absolute" top={1} left={2}>Preview</Text>
                  <Image
                    src={processedImage.processedUrl}
                    alt={`Preview for ${image.productName}`}
                    width="100%"
                    height="100%"
                    objectFit="contain"
                    bg="white"
                    p={4}
                    style={{
                      filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.1))'
                    }}
                  />
                </Box>
              </HStack>
            ) : (
              <Box position="relative" width="100%" height="200px">
                <Image
                  src={image.url}
                  alt={`${image.type} image for ${image.productName}`}
                  width="100%"
                  height="100%"
                  objectFit="contain"
                  bg={imageBg}
                  p={2}
                  transition="transform 0.3s"
                  _hover={{ transform: 'scale(1.05)' }}
                />
                <Tooltip label={isSelected ? 'Deselect Image' : 'Select Image'} placement="top">
                  <Checkbox
                    position="absolute"
                    top={2}
                    right={2}
                    colorScheme="blue"
                    isChecked={isSelected}
                    onChange={() => handleImageSelect(image.id, image.productId)}
                    sx={{
                      '.chakra-checkbox__control': {
                        bg: 'white',
                        opacity: 0.9,
                        _checked: {
                          bg: 'blue.500',
                          opacity: 1,
                          transform: 'scale(1.1)'
                        }
                      }
                    }}
                  />
                </Tooltip>
              </Box>
            )}
          </Box>
          <Box p={4} borderTopWidth="1px">
            <VStack align="start" spacing={1}>
              <HStack width="100%" justify="space-between" align="center">
                <Text fontSize="sm" fontWeight="medium">
                  {image.type === 'main' ? 'Main Image' : 'Gallery Image'}
                </Text>
                {processedImage && (
                  <Badge colorScheme="green" variant="subtle">
                    Processed
                  </Badge>
                )}
              </HStack>
              <Text fontSize="xs" color="gray.500">
                {image.productName}
              </Text>
            </VStack>
          </Box>
        </Box>
      </ScaleFade>
    );
  };

  const SectionHeader = ({ title, count, icon: Icon, rightElement }) => (
    <Box
      p={4}
      borderBottomWidth="1px"
      bg={useColorModeValue('gray.50', 'gray.800')}
      roundedTop="lg"
    >
      <HStack justify="space-between" align="center">
        <HStack spacing={3}>
          <Icon boxSize={5} color={useColorModeValue('blue.500', 'blue.300')} />
          <VStack align="start" spacing={0}>
            <Heading size="sm">{title}</Heading>
            {count !== undefined && (
              <Text fontSize="xs" color="gray.500">
                {count} {count === 1 ? 'item' : 'items'}
              </Text>
            )}
          </VStack>
        </HStack>
        {rightElement}
      </HStack>
    </Box>
  );

  return (
    <Modal
      isOpen={isOpen}
      onClose={handleClose}
      size="6xl"
      closeOnOverlayClick={false}
      closeOnEsc={false}
      isCentered
      motionPreset="scale"
    >
      <ModalOverlay
        bg="blackAlpha.300"
        backdropFilter="blur(10px)"
        transition="all 0.3s"
      />
      <ModalContent
        maxW="1200px"
        bg={modalBg}
        rounded="xl"
        shadow="xl"
        overflow="hidden"
      >
        <ModalHeader
          borderBottomWidth="1px"
          bg={headerBg}
          py={4}
        >
          <HStack spacing={3} justify="space-between" width="100%">
            <HStack spacing={3}>
              <EditIcon color="blue.500" />
              <VStack align="start" spacing={0}>
                <Text>Manage Product Images</Text>
                <Text fontSize="sm" color="gray.500" fontWeight="normal">
                  {products.length} Products Selected
                </Text>
              </VStack>
            </HStack>
            <ButtonGroup size="sm" variant="outline">
              <Button
                leftIcon={viewMode === 'grid' ? <ViewIcon /> : <ViewIcon />}
                onClick={() => setViewMode(viewMode === 'grid' ? 'list' : 'grid')}
              >
                {viewMode === 'grid' ? 'List View' : 'Grid View'}
              </Button>
            </ButtonGroup>
          </HStack>
        </ModalHeader>
        <ModalCloseButton
          isDisabled={isProcessing || isSaving}
          _hover={{ bg: 'red.50', color: 'red.500' }}
        />

        <Box py={2} px={4} borderBottomWidth="1px" bg={useColorModeValue('white', 'gray.800')}>
          <Flex justify="space-between" align="center">
            <HStack spacing={4}>
              <Checkbox
                isChecked={selectAll}
                onChange={handleSelectAll}
                colorScheme="blue"
              >
                <Text fontSize="sm">
                  {selectAll ? 'Deselect All' : 'Select All'}
                </Text>
              </Checkbox>
              {selectedImages.length > 0 && (
                <Badge colorScheme="blue" variant="subtle">
                  {selectedImages.length} selected
                </Badge>
              )}
            </HStack>

            <ButtonGroup size="sm" spacing={2}>
              {selectedImages.length > 0 && !processedImages.length && (
                <Button
                  colorScheme="blue"
                  leftIcon={<EditIcon />}
                  onClick={handleProcessImages}
                  isLoading={isProcessing}
                  loadingText="Processing..."
                >
                  Process {selectedImages.length} Selected
                </Button>
              )}

              {processedImages.length > 0 && (
                <Button
                  colorScheme="green"
                  leftIcon={<ArrowForwardIcon />}
                  onClick={handleSave}
                  isLoading={isSaving}
                  loadingText={`Saving... ${saveProgress}%`}
                >
                  Save {processedImages.length} Processed
                </Button>
              )}
            </ButtonGroup>
          </Flex>
        </Box>

        <ModalBody py={6}>
          <VStack spacing={6} align="stretch">
            {error && (
              <Alert
                status="error"
                variant="left-accent"
                rounded="lg"
                shadow="sm"
              >
                <AlertIcon />
                {error}
              </Alert>
            )}

            {allImages.length === 0 ? (
              <Box
                textAlign="center"
                py={12}
                bg={useColorModeValue('white', 'gray.800')}
                rounded="xl"
                borderWidth="1px"
                px={6}
              >
                <WarningIcon boxSize={12} color="orange.400" mb={6} />
                <Heading size="md" mb={3}>
                  No images found
                </Heading>
                <Text color="gray.500">
                  None of the selected products have any images.
                </Text>
              </Box>
            ) : (
              <Grid
                templateColumns={viewMode === 'grid' ? 'repeat(auto-fill, minmax(250px, 1fr))' : '1fr'}
                gap={6}
              >
                {allImages.map((image, index) => (
                  <GridItem key={`${image.productId}-${image.id}`}>
                    {renderImageCard(image)}
                  </GridItem>
                ))}
              </Grid>
            )}

            {renderProgressIndicator()}
            {renderSavingProgressIndicator()}
          </VStack>
        </ModalBody>

        <ModalFooter
          borderTopWidth="1px"
          bg={useColorModeValue('white', 'gray.800')}
          roundedBottom="md"
        >
          <Button
            variant="ghost"
            mr={3}
            onClick={handleClose}
            isDisabled={isProcessing || isSaving}
            leftIcon={<SmallCloseIcon />}
            _hover={{ bg: 'red.50', color: 'red.500' }}
          >
            Close
          </Button>
          {renderProgressIndicator()}
          {renderSavingProgressIndicator()}
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
};

export default ProductImagesModal;