import React, { useState, useEffect } from 'react';
import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Button,
  Input,
  VStack,
  FormControl,
  FormLabel,
  FormErrorMessage,
  useToast,
  Text,
  Box,
  List,
  ListItem,
  HStack,
  IconButton
} from '@chakra-ui/react';
import { CheckIcon, StarIcon } from '@chakra-ui/icons';

const ManufacturerModal = ({ isOpen, onClose, product, onManufacturerUpdated }) => {
  const [manufacturer, setManufacturer] = useState('');
  const [isSaving, setIsSaving] = useState(false);
  const [recentManufacturers, setRecentManufacturers] = useState([]);
  const toast = useToast();

  // Reset manufacturer when modal opens
  useEffect(() => {
    if (isOpen && product) {
      setManufacturer(product.manufacturer || '');
      loadRecentManufacturers();
    }
  }, [isOpen, product]);

  const loadRecentManufacturers = async () => {
    try {
      const response = await fetch('/wp-json/klcnn/v1/manufacturers/recent', {
        headers: {
          'X-WP-Nonce': window.klcnnData.nonce
        }
      });

      if (!response.ok) throw new Error('Failed to load recent manufacturers');

      const data = await response.json();
      setRecentManufacturers(data);
    } catch (error) {
      console.error('Error loading recent manufacturers:', error);
    }
  };

  const handleSave = async () => {
    if (!manufacturer.trim()) {
      toast({
        title: "Invalid Manufacturer",
        description: "Please enter a manufacturer name",
        status: "error",
        duration: 3000
      });
      return;
    }

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

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

      toast({
        title: "Manufacturer Updated",
        description: "Product manufacturer has been updated successfully",
        status: "success",
        duration: 3000
      });

      if (onManufacturerUpdated) {
        onManufacturerUpdated(product.id, manufacturer.trim());
      }
      onClose();
    } catch (error) {
      toast({
        title: "Update Failed",
        description: error.message,
        status: "error",
        duration: 3000
      });
    } finally {
      setIsSaving(false);
    }
  };

  const handleSelectManufacturer = (selectedManufacturer) => {
    setManufacturer(selectedManufacturer);
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose}>
      <ModalOverlay />
      <ModalContent>
        <ModalHeader>Set Manufacturer for {product?.name}</ModalHeader>
        <ModalBody>
          <VStack spacing={4}>
            <FormControl isInvalid={!manufacturer.trim()}>
              <FormLabel>Manufacturer Name</FormLabel>
              <Input
                value={manufacturer}
                onChange={(e) => setManufacturer(e.target.value)}
                placeholder="Enter manufacturer name"
              />
              {!manufacturer.trim() && (
                <FormErrorMessage>
                  Manufacturer name is required
                </FormErrorMessage>
              )}
            </FormControl>

            {recentManufacturers.length > 0 && (
              <Box width="100%">
                <Text fontWeight="bold" mb={2}>Recent Manufacturers:</Text>
                <List spacing={2}>
                  {recentManufacturers.map((recentMfg, index) => (
                    <ListItem key={index}>
                      <HStack>
                        <Button
                          size="sm"
                          variant="ghost"
                          leftIcon={manufacturer === recentMfg ? <CheckIcon /> : <StarIcon />}
                          onClick={() => handleSelectManufacturer(recentMfg)}
                          width="100%"
                          justifyContent="flex-start"
                        >
                          {recentMfg}
                        </Button>
                      </HStack>
                    </ListItem>
                  ))}
                </List>
              </Box>
            )}
          </VStack>
        </ModalBody>

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

export default ManufacturerModal;