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

const CategoryModal = ({ isOpen, onClose, product, onCategoryUpdated }) => {
  const [selectedCategory, setSelectedCategory] = React.useState(null);
  const [isSaving, setIsSaving] = React.useState(false);
  const toast = useToast();

  // Reset selected category when modal opens
  React.useEffect(() => {
    if (isOpen) {
      setSelectedCategory(null);
    }
  }, [isOpen]);

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

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

      if (!response.ok) {
        throw new Error('Failed to update category');
      }

      const responseData = await response.json();

      // Call the callback to update the product in the table
      onCategoryUpdated(product.id, selectedCategory);

      toast({
        title: 'Category updated',
        description: `Category set to: ${selectedCategory.title_singular}`,
        status: 'success',
        duration: 3000
      });

      onClose();
    } catch (error) {
      console.error('Save error:', error);
      toast({
        title: 'Error updating category',
        description: error.message,
        status: 'error',
        duration: 3000
      });
    } finally {
      setIsSaving(false);
    }
  };

  if (!product) return null;

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

        <ModalBody>
          <VStack align="stretch" spacing={4}>
            <Text>
              <strong>Product:</strong> {product.name}
            </Text>
            <Text>
              <strong>Current Category:</strong> {' '}
              {product.kaufland_category || 'Not set'}
            </Text>

            <CategorySelector
              product={product}
              onCategorySelect={setSelectedCategory}
            />
          </VStack>
        </ModalBody>

        <ModalFooter>
          <Button variant="ghost" mr={3} onClick={onClose}>
            Cancel
          </Button>
          <Button
            colorScheme="blue"
            onClick={handleSave}
            isLoading={isSaving}
            isDisabled={!selectedCategory}
          >
            Save
          </Button>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
};

export default CategoryModal;