import React, { useRef, useEffect, useState } from 'react';
import JsBarcode from 'jsbarcode';
import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Button,
  Input,
  VStack,
  HStack,
  useToast,
  FormControl,
  FormLabel,
  FormErrorMessage,
  Text,
  Select,
  Tooltip
} from '@chakra-ui/react';

// Kaufland supported countries with their GS1 prefixes
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'] }
];

// EAN-13 validation function
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]);
};

// Generate check digit for EAN-13
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 EanModal = ({ isOpen, onClose, product, onEanUpdated }) => {
  const [ean, setEan] = useState('');
  const [selectedCountry, setSelectedCountry] = useState('DE');
  const [isSaving, setIsSaving] = useState(false);
  const barcodeRef = useRef();
  const toast = useToast();

  // Reset EAN when modal opens
  useEffect(() => {
    if (isOpen && product) {
      setEan(product.ean || '');
    }
  }, [isOpen, product]);

  // Generate barcode when EAN changes
  useEffect(() => {
    const cleanEan = String(ean).replace(/\D/g, '');
    if (cleanEan.length === 13 && validateEAN(cleanEan)) {
      try {
        JsBarcode(barcodeRef.current, cleanEan, {
          format: "EAN13",
          width: 2,
          height: 100,
          displayValue: true
        });
      } catch (error) {
        console.error('Barcode generation error:', error);
      }
    }
  }, [ean]);

  const handleEanChange = (e) => {
    const value = e.target.value;
    // Only allow numbers and limit to 13 digits
    const cleanValue = value.replace(/\D/g, '').slice(0, 13);
    setEan(cleanValue);
  };

  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);
    setEan(eanWithoutCheck + checkDigit);
  };

  const handleSave = async () => {
    const cleanEan = String(ean).replace(/\D/g, '');
    if (!validateEAN(cleanEan)) {
      toast({
        title: "Invalid EAN",
        description: "Please enter a valid EAN-13 number",
        status: "error",
        duration: 3000
      });
      return;
    }

    setIsSaving(true);
    try {
      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: cleanEan })
      });

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

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

  const getSelectedCountryPrefixes = () => {
    const country = COUNTRY_PREFIXES.find(c => c.code === selectedCountry);
    return country ? country.prefixes.join(', ') : '';
  };

  // Check if the current EAN starts with a valid prefix for the selected country
  const isValidCountryPrefix = () => {
    const cleanEan = String(ean).replace(/\D/g, '');
    if (cleanEan.length < 3) return true; // Not enough digits to check

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

    return country.prefixes.some(prefix => cleanEan.startsWith(prefix));
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose}>
      <ModalOverlay />
      <ModalContent>
        <ModalHeader>Set EAN for {product?.name}</ModalHeader>
        <ModalBody>
          <VStack spacing={4}>
            <FormControl>
              <FormLabel>Country</FormLabel>
              <Select
                value={selectedCountry}
                onChange={(e) => setSelectedCountry(e.target.value)}
              >
                {COUNTRY_PREFIXES.map(country => (
                  <option key={country.code} value={country.code}>
                    {country.name}
                  </option>
                ))}
              </Select>
            </FormControl>

            <FormControl isInvalid={ean && (!validateEAN(ean) || !isValidCountryPrefix())}>
              <FormLabel>EAN-13</FormLabel>
              <HStack>
                <Input
                  value={ean}
                  onChange={handleEanChange}
                  placeholder="Enter EAN"
                  maxLength={13}
                />
                <Tooltip label={`Generate EAN with prefix: ${getSelectedCountryPrefixes()}`}>
                  <Button
                    onClick={generateRandomEAN}
                    colorScheme="blue"
                    variant="outline"
                  >
                    Generate
                  </Button>
                </Tooltip>
              </HStack>
              {ean && !validateEAN(ean) && (
                <FormErrorMessage>
                  Please enter a valid EAN-13 number
                </FormErrorMessage>
              )}
              {ean && validateEAN(ean) && !isValidCountryPrefix() && (
                <FormErrorMessage>
                  EAN prefix does not match selected country
                </FormErrorMessage>
              )}
            </FormControl>

            {/* Barcode Preview */}
            <svg ref={barcodeRef}></svg>

            <Text fontSize="sm" color="gray.600">
              Using {COUNTRY_PREFIXES.find(c => c.code === selectedCountry)?.name} prefix(es): {getSelectedCountryPrefixes()}
            </Text>
          </VStack>
        </ModalBody>

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

export default EanModal;