import React, { useState } from 'react';
import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalFooter,
  ModalCloseButton,
  Button,
  Text,
  VStack,
  Box,
  useToast,
  Table,
  Thead,
  Tbody,
  Tr,
  Th,
  Td,
  Input,
  Select,
  HStack,
  Tooltip
} from '@chakra-ui/react';

// Import the same country prefixes from EanModal
const COUNTRY_PREFIXES = [
  { code: 'DE', name: 'Germany', prefixes: ['400', '401', '402', '403', '404', '405'] },
  { code: 'CZ', name: 'Czech Republic', prefixes: ['859'] },
  { code: 'SK', name: 'Slovakia', prefixes: ['858'] },
  { code: 'PL', name: 'Poland', prefixes: ['590'] },
  { code: 'HR', name: 'Croatia', prefixes: ['385'] },
  { code: 'RO', name: 'Romania', prefixes: ['594'] },
  { code: 'BG', name: 'Bulgaria', prefixes: ['380'] },
  { code: 'MD', name: 'Moldova', prefixes: ['484'] }
];

const BulkEanModal = ({ isOpen, onClose, products, onEansUpdated, onComplete }) => {
  const [selectedCountry, setSelectedCountry] = useState('DE');
  const [productEans, setProductEans] = useState({});
  const [isSaving, setIsSaving] = useState(false);
  const toast = useToast();

  // Initialize productEans when modal opens
  React.useEffect(() => {
    if (isOpen && products) {
      const initialEans = {};
      products.forEach(product => {
        initialEans[product.id] = product.ean || '';
      });
      setProductEans(initialEans);
    }
  }, [isOpen, products]);

  const validateEAN = (ean) => {
    // Convert to string and clean input
    const cleanEan = String(ean).replace(/\D/g, '');

    if (cleanEan.length !== 13) {
      return false;
    }

    // Calculate check digit
    let sum = 0;
    for (let i = 0; i < 12; i++) {
      sum += parseInt(cleanEan[i]) * (i % 2 === 0 ? 1 : 3);
    }
    const checkDigit = (10 - (sum % 10)) % 10;

    return checkDigit === parseInt(cleanEan[12]);
  };

  const generateCheckDigit = (eanWithoutCheck) => {
    const cleanEan = String(eanWithoutCheck).replace(/\D/g, '');
    let sum = 0;
    for (let i = 0; i < 12; i++) {
      sum += parseInt(cleanEan[i]) * (i % 2 === 0 ? 1 : 3);
    }
    return (10 - (sum % 10)) % 10;
  };

  const generateRandomEAN = () => {
    const country = COUNTRY_PREFIXES.find(c => c.code === selectedCountry);
    if (!country) return '';

    // Randomly select one prefix if multiple are available
    const prefix = country.prefixes[Math.floor(Math.random() * country.prefixes.length)];

    // Calculate remaining digits needed (12 - prefix length)
    const remainingLength = 12 - prefix.length;
    const randomPart = Array.from({ length: remainingLength }, () =>
      Math.floor(Math.random() * 10)).join('');

    const eanWithoutCheck = prefix + randomPart;
    const checkDigit = generateCheckDigit(eanWithoutCheck);
    return eanWithoutCheck + checkDigit;
  };

  const handleGenerateAll = () => {
    const newEans = { ...productEans };
    products.forEach(product => {
      if (!newEans[product.id]) {
        newEans[product.id] = generateRandomEAN();
      }
    });
    setProductEans(newEans);
  };

  const handleSave = async () => {
    setIsSaving(true);
    const successfulUpdates = [];
    const failedUpdates = [];

    for (const product of products) {
      const ean = productEans[product.id];
      if (!ean || !validateEAN(ean)) continue;

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

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

        successfulUpdates.push({ id: product.id, ean });
      } catch (error) {
        failedUpdates.push({ id: product.id, error: error.message });
      }
    }

    if (successfulUpdates.length > 0) {
      // Update UI
      onEansUpdated(successfulUpdates);

      toast({
        title: 'EANs updated',
        description: `Updated ${successfulUpdates.length} products${failedUpdates.length > 0 ? `, ${failedUpdates.length} failed` : ''}`,
        status: 'success',
        duration: 3000
      });
    }

    if (failedUpdates.length > 0) {
      toast({
        title: 'Some EANs failed to update',
        description: `${failedUpdates.length} updates failed`,
        status: 'error',
        duration: 3000
      });
    }

    setIsSaving(false);
    onClose();

    // If all products have valid EANs now, call onComplete
    if (successfulUpdates.length === products.length) {
      onComplete();
    }
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} size="xl">
      <ModalOverlay />
      <ModalContent maxW="900px">
        <ModalHeader>Set EANs for Selected Products</ModalHeader>
        <ModalCloseButton />

        <ModalBody>
          <VStack spacing={4}>
            <HStack spacing={4} width="100%">
              <Select
                value={selectedCountry}
                onChange={(e) => setSelectedCountry(e.target.value)}
              >
                {COUNTRY_PREFIXES.map(country => (
                  <option key={country.code} value={country.code}>
                    {country.name}
                  </option>
                ))}
              </Select>
              <Button onClick={handleGenerateAll}>
                Generate Missing EANs
              </Button>
            </HStack>

            <Box overflowX="auto" width="100%">
              <Table variant="simple">
                <Thead>
                  <Tr>
                    <Th>Product</Th>
                    <Th>EAN</Th>
                    <Th>Actions</Th>
                  </Tr>
                </Thead>
                <Tbody>
                  {products.map(product => (
                    <Tr key={product.id}>
                      <Td>{product.name}</Td>
                      <Td>
                        <Input
                          value={productEans[product.id] || ''}
                          onChange={(e) => {
                            const value = e.target.value.replace(/\D/g, '').slice(0, 13);
                            setProductEans(prev => ({
                              ...prev,
                              [product.id]: value
                            }));
                          }}
                          isInvalid={productEans[product.id] && !validateEAN(productEans[product.id])}
                          placeholder="Enter EAN"
                        />
                      </Td>
                      <Td>
                        <Button
                          size="sm"
                          onClick={() => {
                            setProductEans(prev => ({
                              ...prev,
                              [product.id]: generateRandomEAN()
                            }));
                          }}
                        >
                          Generate
                        </Button>
                      </Td>
                    </Tr>
                  ))}
                </Tbody>
              </Table>
            </Box>
          </VStack>
        </ModalBody>

        <ModalFooter>
          <Button variant="ghost" mr={3} onClick={onClose}>
            Cancel
          </Button>
          <Button
            colorScheme="blue"
            onClick={handleSave}
            isLoading={isSaving}
            isDisabled={!Object.values(productEans).some(ean => validateEAN(ean))}
          >
            Save & Continue
          </Button>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
};

export default BulkEanModal;