import React from 'react';
import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Button,
  VStack,
  HStack,
  Text,
  FormControl,
  FormLabel,
  Input,
  Select,
  useToast,
  Box,
  Divider,
  Badge,
  Icon,
  Collapse,
  Alert,
  AlertIcon,
  Grid,
} from '@chakra-ui/react';
import { FiGlobe, FiKey, FiCheck, FiAlertCircle, FiLock } from 'react-icons/fi';
import { MARKETPLACES, getDefaultMarketplace } from '../../config/marketplaces.js';
import { API_ENDPOINTS } from '../../config/endpoints';

const MarketplaceCard = ({ market, isSelected, onClick, isAvailable = true }) => (
  <Box position="relative">
    <Box
      p={1.5}
      bg={isSelected ? 'blue.50' : 'white'}
      borderWidth={1}
      borderColor={isSelected ? 'blue.500' : 'gray.200'}
      rounded="md"
      cursor={isAvailable ? 'pointer' : 'not-allowed'}
      onClick={isAvailable ? onClick : undefined}
      transition="all 0.2s"
      _hover={isAvailable ? {
        transform: 'translateY(-1px)',
        shadow: 'sm',
      } : {}}
      opacity={isAvailable ? 1 : 0.7}
    >
      <VStack spacing={0} align="stretch">
        <HStack justify="space-between">
          <Text fontSize="lg">{market.flag}</Text>
          {isSelected && (
            <Icon
              as={FiCheck}
              color="blue.500"
              boxSize={2.5}
            />
          )}
        </HStack>
        <Text fontSize="2xs" fontWeight="bold">{market.name}</Text>
        <Text fontSize="2xs" color="gray.500" noOfLines={1}>{market.domain}</Text>
      </VStack>
    </Box>
    {!isAvailable && (
      <Box
        position="absolute"
        top="0"
        left="0"
        right="0"
        bottom="0"
        display="flex"
        alignItems="center"
        justifyContent="center"
        bg="blackAlpha.50"
        rounded="md"
      >
        <HStack spacing={1}>
          <Icon as={FiLock} fontSize="2xs" />
          <Text fontSize="2xs" fontWeight="medium">Coming Soon</Text>
        </HStack>
      </Box>
    )}
  </Box>
);

const ConnectionWizard = ({ isOpen, onClose, onSave }) => {
  const toast = useToast();
  const storeCountry = window.klcnnData?.storeLocation?.country || 'DE';
  const defaultCountry = React.useMemo(
    () => getDefaultMarketplace(storeCountry),
    [storeCountry]
  );

  const [selectedMarketplace, setSelectedMarketplace] = React.useState(defaultCountry);
  const [credentials, setCredentials] = React.useState({
    clientId: '',
    clientSecret: ''
  });
  const [isLoading, setIsLoading] = React.useState(false);
  const [testStatus, setTestStatus] = React.useState(null);

  const handleCredentialsChange = (e) => {
    const { name, value } = e.target;
    setCredentials(prev => ({
      ...prev,
      [name]: value
    }));
    setTestStatus(null);
  };

  const handleTestConnection = async () => {
    setIsLoading(true);
    try {
      const response = await fetch('/wp-json/klcnn/v1/categories', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': window.klcnnData.nonce
        },
        body: JSON.stringify({
          clientKey: credentials.clientId,
          secretKey: credentials.clientSecret,
          marketplace: selectedMarketplace
        })
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || 'Connection failed');
      }

      setTestStatus('success');
      toast({
        title: 'Connection successful',
        description: 'Successfully connected to Kaufland API',
        status: 'success',
        duration: 3000
      });
    } catch (error) {
      setTestStatus('error');
      toast({
        title: 'Connection failed',
        description: error.message,
        status: 'error',
        duration: 3000
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleSaveConnection = async () => {
    if (testStatus !== 'success') {
      toast({
        title: 'Test Required',
        description: 'Please test the connection before saving',
        status: 'warning',
        duration: 3000
      });
      return;
    }

    try {
      await onSave({
        clientId: credentials.clientId,
        clientSecret: credentials.clientSecret,
        marketplace: selectedMarketplace
      });
    } catch (error) {
      toast({
        title: 'Save Failed',
        description: error.message,
        status: 'error',
        duration: 3000
      });
    }
  };

  // Reset form when modal closes
  React.useEffect(() => {
    if (!isOpen) {
      setCredentials({
        clientId: '',
        clientSecret: ''
      });
      setTestStatus(null);
      setSelectedMarketplace(defaultCountry);
    }
  }, [isOpen, defaultCountry]);

  // Sort marketplaces to show default first
  const sortedMarketplaces = React.useMemo(() => {
    const entries = Object.entries(MARKETPLACES);
    return entries.sort(([keyA], [keyB]) => {
      if (keyA === defaultCountry) return -1;
      if (keyB === defaultCountry) return 1;
      return 0;
    });
  }, [defaultCountry]);

  // Define available marketplaces (for now, only the default country)
  const availableMarketplaces = React.useMemo(() => {
    return [defaultCountry];
  }, [defaultCountry]);

  // Add warning if store country doesn't have Kaufland marketplace
  const showUnavailableWarning = React.useMemo(() => {
    return !Object.values(MARKETPLACES).some(
      market => market.countryCode === storeCountry
    );
  }, [storeCountry]);

  return (
    <Modal isOpen={isOpen} onClose={onClose} size="xl">
      <ModalOverlay />
      <ModalContent>
        <ModalHeader>
          <HStack>
            <Icon as={FiGlobe} />
            <Text>Connect to Kaufland Marketplace</Text>
          </HStack>
        </ModalHeader>

        <ModalBody>
          <VStack spacing={3} align="stretch">
            {showUnavailableWarning && (
              <Alert status="warning" variant="subtle" rounded="md">
                <AlertIcon />
                <Text fontSize="sm">
                  Kaufland Marketplace is not available in your store's country ({storeCountry}).
                  Please select an available marketplace.
                </Text>
              </Alert>
            )}

            {/* Marketplace Selection */}
            <Box>
              <FormLabel>
                <HStack mb={1}>
                  <Icon as={FiGlobe} boxSize={3} />
                  <Text fontSize="sm">Select Marketplace</Text>
                </HStack>
              </FormLabel>
              <Grid
                templateColumns="repeat(3, 1fr)"
                gap={1.5}
              >
                {sortedMarketplaces.map(([key, market]) => (
                  <MarketplaceCard
                    key={key}
                    market={market}
                    isSelected={selectedMarketplace === key}
                    onClick={() => setSelectedMarketplace(key)}
                    isAvailable={availableMarketplaces.includes(key)}
                  />
                ))}
              </Grid>
            </Box>

            {/* API Credentials */}
            <Box
              p={2}
              bg="gray.50"
              rounded="md"
              borderWidth={1}
              borderColor="gray.200"
            >
              <VStack spacing={2} align="stretch">
                <HStack>
                  <Icon as={FiKey} boxSize={3} />
                  <Text fontSize="sm" fontWeight="bold">API Credentials</Text>
                </HStack>

                <FormControl isRequired>
                  <FormLabel fontSize="sm">Client ID</FormLabel>
                  <Input
                    size="sm"
                    name="clientId"
                    value={credentials.clientId}
                    onChange={handleCredentialsChange}
                    placeholder="Enter your client ID"
                    bg="white"
                  />
                </FormControl>

                <FormControl isRequired>
                  <FormLabel fontSize="sm">Client Secret</FormLabel>
                  <Input
                    size="sm"
                    name="clientSecret"
                    type="password"
                    value={credentials.clientSecret}
                    onChange={handleCredentialsChange}
                    placeholder="Enter your client secret"
                    bg="white"
                  />
                </FormControl>
              </VStack>
            </Box>

            {/* Connection Status */}
            <Collapse in={testStatus !== null}>
              <Alert
                status={testStatus === 'success' ? 'success' : 'error'}
                variant="subtle"
                rounded="md"
              >
                <AlertIcon />
                {testStatus === 'success'
                  ? 'Connection successful! You can now save your settings.'
                  : 'Connection failed. Please check your credentials and try again.'}
              </Alert>
            </Collapse>
          </VStack>
        </ModalBody>

        <ModalFooter>
          <HStack spacing={4}>
            <Button size="sm" variant="ghost" onClick={onClose}>
              Cancel
            </Button>
            <Button
              size="sm"
              leftIcon={<Icon as={FiCheck} />}
              colorScheme="blue"
              onClick={handleTestConnection}
              isLoading={isLoading}
              isDisabled={!credentials.clientId || !credentials.clientSecret}
            >
              Test Connection
            </Button>
            <Button
              size="sm"
              colorScheme="green"
              onClick={handleSaveConnection}
              isDisabled={testStatus !== 'success'}
            >
              Save Connection
            </Button>
          </HStack>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
};

export default ConnectionWizard;