import React from 'react';
import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalFooter,
  ModalCloseButton,
  Button,
  Text,
  VStack,
  Box,
  useToast,
  List,
  ListItem,
  Divider
} from '@chakra-ui/react';
import CategorySelector from './CategorySelector';

const BulkCategoryModal = ({ isOpen, onClose, selectedProducts, products, onCategoriesUpdated }) => {
  const [selectedCategory, setSelectedCategory] = React.useState(null);
  const toast = useToast();

  // Get the full product details for selected products
  const selectedProductDetails = products.filter(p => selectedProducts.includes(p.id));

  const handleSave = async () => {
    if (!selectedCategory) return;

    try {
      const response = await fetch('/wp-json/klcnn/v1/products/bulk-category', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': window.klcnnData.nonce
        },
        body: JSON.stringify({
          product_ids: selectedProducts,
          category_id: selectedCategory.id_category,
          category_name: selectedCategory.name,
          category_title: selectedCategory.title_singular
        })
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || 'Failed to update categories');
      }

      const data = await response.json();

      // Update UI for all updated products
      if (data.data.updated && onCategoriesUpdated) {
        data.data.updated.forEach(product => {
          onCategoriesUpdated(product.id, {
            id_category: product.category_id,
            name: product.category_name,
            title_singular: product.category_title
          });
        });
      }

      toast({
        title: 'Categories updated',
        description: data.message || `Updated categories for ${selectedProducts.length} products`,
        status: 'success',
        duration: 3000
      });

      onClose();
    } catch (error) {
      toast({
        title: 'Error updating categories',
        description: error.message,
        status: 'error',
        duration: 3000
      });
    }
  };

  // Use the first product as a reference for category suggestions
  const referenceProduct = selectedProductDetails[0];

  return (
    <Modal isOpen={isOpen} onClose={onClose} size="xl">
      <ModalOverlay />
      <ModalContent>
        <ModalHeader>Set Category for Multiple Products</ModalHeader>
        <ModalCloseButton />

        <ModalBody>
          <VStack align="stretch" spacing={4}>
            <Box p={4} bg="gray.50" borderRadius="md">
              <Text fontWeight="bold" mb={2}>
                Selected Products ({selectedProducts.length}):
              </Text>
              <List spacing={2}>
                {selectedProductDetails.slice(0, 5).map(product => (
                  <ListItem key={product.id}>
                    {product.name}
                    {product.kaufland_category && (
                      <Text as="span" color="gray.500" ml={2}>
                        (Current: {product.kaufland_category})
                      </Text>
                    )}
                  </ListItem>
                ))}
                {selectedProductDetails.length > 5 && (
                  <ListItem color="gray.500">
                    And {selectedProductDetails.length - 5} more products...
                  </ListItem>
                )}
              </List>
            </Box>

            <Divider />

            <Text fontWeight="bold">Select Category for All Products:</Text>
            {referenceProduct && (
              <CategorySelector
                product={referenceProduct}
                onCategorySelect={setSelectedCategory}
              />
            )}
          </VStack>
        </ModalBody>

        <ModalFooter>
          <Button variant="ghost" mr={3} onClick={onClose}>
            Cancel
          </Button>
          <Button
            colorScheme="blue"
            onClick={handleSave}
            isDisabled={!selectedCategory}
          >
            Apply to All Selected Products
          </Button>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
};

export default BulkCategoryModal;