import React, { useEffect } from 'react';
import {
  FormControl,
  FormLabel,
  Select,
  NumberInput,
  NumberInputField,
  NumberInputStepper,
  NumberIncrementStepper,
  NumberDecrementStepper,
  VStack,
  Text,
  InputGroup,
  InputLeftAddon,
  Box,
  useColorModeValue,
  Icon,
  Tooltip,
  Badge,
  FormHelperText,
  Flex,
  RadioGroup,
  Radio,
  Stack,
  Switch,
  HStack,
  Button
} from '@chakra-ui/react';
import { InfoIcon } from '@chakra-ui/icons';
import { getDiscountOptions } from '../RuleEditor/options';

const confettiStyles = [
  { id: 'none', label: 'No Celebration' },
  { id: 'basic', label: 'Basic Celebration' },
  { id: 'fireworks', label: 'Fireworks Show' },
  { id: 'sparkles', label: 'Sparkles Rain' },
  { id: 'party', label: 'Party Time' },
  { id: 'rainbow', label: 'Rainbow Wave' },
  { id: 'stars', label: 'Shooting Stars' },
  { id: 'hearts', label: 'Love Hearts' },
  { id: 'glitter', label: 'Golden Glitter' },
  { id: 'explosion', label: 'Color Explosion' },
  { id: 'snow', label: 'Gentle Snow' },
  { id: 'bubbles', label: 'Rising Bubbles' }
];

const DiscountSettings = ({ formData, onChange }) => {
  const helperTextColor = useColorModeValue('gray.600', 'gray.400');
  const borderColor = useColorModeValue('gray.200', 'gray.600');
  const bgHover = useColorModeValue('gray.50', 'gray.700');
  const radioBg = useColorModeValue('white', 'gray.700');
  const isValidDiscount = formData.discountValue > 0;

  const triggerPreview = React.useCallback(() => {
    if (typeof window.confetti === 'undefined') {
      const script = document.createElement('script');
      script.src = 'https://cdn.jsdelivr.net/npm/canvas-confetti@1.6.0/dist/confetti.browser.min.js';
      script.onload = () => {
        triggerCelebration();
      };
      document.body.appendChild(script);
    } else {
      triggerCelebration();
    }
  }, [formData.celebrationType]);

  const triggerCelebration = () => {
    const defaults = {
      origin: { y: 0.7 },
      spread: 90,
      startVelocity: 30,
      zIndex: 300
    };

    switch (formData.celebrationType) {
      case 'rainbow':
        // Rainbow wave effect
        const colors = ['#ff0000', '#ff9900', '#ffff00', '#33cc33', '#3399ff', '#9933ff'];
        for (let i = 0; i < 3; i++) {
          setTimeout(() => {
            window.confetti({
              ...defaults,
              particleCount: 40,
              spread: 80,
              origin: { x: 0.2 + (i * 0.3), y: 0.7 },
              colors: colors,
              ticks: 300,
              startVelocity: 35,
              shapes: ['circle'],
              scalar: 1.2
            });
          }, i * 200);
        }
        break;

      case 'stars':
        // Shooting stars effect
        const starDefaults = {
          ...defaults,
          shapes: ['star'],
          colors: ['#FFD700', '#FFF8DC', '#FFE4B5'],
          gravity: 0.4,
          scalar: 1.4,
          drift: 1
        };

        for (let i = 0; i < 3; i++) {
          setTimeout(() => {
            window.confetti({
              ...starDefaults,
              particleCount: 15,
              spread: 40,
              startVelocity: 35 + (i * 10),
              origin: { x: 0.2 + (i * 0.3), y: 0.7 }
            });
          }, i * 300);
        }
        break;

      case 'hearts':
        // Love hearts shower
        const heartColors = ['#ff69b4', '#ff1493', '#ff0000', '#ff69b4'];
        for (let i = 0; i < 3; i++) {
          setTimeout(() => {
            window.confetti({
              ...defaults,
              particleCount: 25,
              spread: 60,
              shapes: ['heart'],
              colors: heartColors,
              scalar: 2,
              drift: 0.5,
              ticks: 300,
              origin: { x: 0.2 + (i * 0.3), y: 0.7 }
            });
          }, i * 200);
        }
        break;

      case 'glitter':
        // Golden glitter burst
        const glitterDefaults = {
          ...defaults,
          colors: ['#FFD700', '#DAA520', '#FDB813', '#F4C430'],
          gravity: 0.6,
          scalar: 0.7,
          drift: 0.2,
          ticks: 150
        };

        for (let i = 0; i < 5; i++) {
          setTimeout(() => {
            window.confetti({
              ...glitterDefaults,
              particleCount: 30,
              spread: 50,
              startVelocity: 25 + (i * 5),
              origin: { x: 0.2 + (Math.random() * 0.6), y: 0.7 }
            });
          }, i * 150);
        }
        break;

      case 'explosion':
        // Color explosion
        const explosionColors = [
          '#FF1461', '#18FF92', '#1A8FE3', '#FFE700', '#FF7C00',
          '#FF005D', '#45FFA0', '#00B1E9', '#FFD300', '#FF8E00'
        ];

        for (let i = 0; i < 3; i++) {
          setTimeout(() => {
            window.confetti({
              ...defaults,
              particleCount: 80,
              spread: 100 + (i * 30),
              origin: { x: 0.5, y: 0.7 },
              colors: explosionColors,
              ticks: 200,
              gravity: 1,
              scalar: 1.2 - (i * 0.2),
              shapes: ['circle', 'square'],
              startVelocity: 40 + (i * 10)
            });
          }, i * 150);
        }
        break;

      case 'snow':
        // Gentle snow effect
        const snowColors = ['#ffffff', '#f0f0f0', '#e0e0e0'];
        for (let i = 0; i < 5; i++) {
          setTimeout(() => {
            window.confetti({
              ...defaults,
              particleCount: 30,
              spread: 70,
              origin: { x: 0.2 + (Math.random() * 0.6), y: 0.7 },
              colors: snowColors,
              ticks: 400,
              gravity: 0.3,
              scalar: 0.8,
              drift: 2,
              shapes: ['circle']
            });
          }, i * 200);
        }
        break;

      case 'bubbles':
        // Rising bubbles effect
        const bubbleColors = ['#8FDBFF', '#4FC3F7', '#29B6F6', '#03A9F4'];
        for (let i = 0; i < 4; i++) {
          setTimeout(() => {
            window.confetti({
              ...defaults,
              particleCount: 20,
              spread: 60,
              origin: { x: 0.2 + (Math.random() * 0.6), y: 0.7 },
              colors: bubbleColors,
              ticks: 300,
              gravity: -0.2,
              scalar: 1.5,
              drift: 0.5,
              shapes: ['circle']
            });
          }, i * 150);
        }
        break;

      case 'fireworks':
        window.confetti({
          ...defaults,
          spread: 360,
          ticks: 200,
          gravity: 0.5,
          decay: 0.94,
          startVelocity: 30,
          particleCount: 100,
          scalar: 1.2,
          shapes: ['star'],
          colors: ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff']
        });
        break;

      case 'sparkles':
        window.confetti({
          ...defaults,
          spread: 100,
          particleCount: 40,
          ticks: 200,
          origin: { x: 0.4, y: 0.7 },
          colors: ['#FFD700', '#FFA500', '#FF6347']
        });
        window.confetti({
          ...defaults,
          spread: 100,
          particleCount: 40,
          ticks: 200,
          origin: { x: 0.6, y: 0.7 },
          colors: ['#FFD700', '#FFA500', '#FF6347']
        });
        break;

      case 'party':
        window.confetti({
          ...defaults,
          spread: 100,
          particleCount: 100,
          origin: { y: 0.8 },
          colors: ['#FF1461', '#18FF92', '#1A8FE3', '#FFE700', '#FF7C00'],
          ticks: 200,
          gravity: 1.2,
          scalar: 1.2,
          drift: 0
        });
        break;

      case 'basic':
      default:
        window.confetti({
          ...defaults,
          particleCount: 100,
          spread: 70,
          ticks: 200,
          colors: ['#FFD700', '#FFA500', '#FF6347', '#87CEEB', '#98FB98']
        });
        break;
    }
  };

  const handleCelebrationTypeChange = (value) => {
    onChange('celebrationType', value);
  };

  return (
    <Box
      borderWidth="1px"
      borderColor={borderColor}
      borderRadius="lg"
      p={6}
      _hover={{ bg: bgHover }}
      transition="background 0.2s"
    >
      <VStack spacing={6} align="stretch">
        <Box>
          <Text fontSize="lg" fontWeight="medium" mb={4}>
            Discount Settings
            <Badge ml={2} colorScheme={isValidDiscount ? 'green' : 'orange'} variant="subtle">
              {isValidDiscount ? 'Active' : 'Set Amount'}
            </Badge>
          </Text>
        </Box>

        <FormControl>
          <FormLabel fontWeight="medium">
            Discount Type
            <Tooltip
              label="Choose how you want to apply the discount"
              placement="top"
              hasArrow
            >
              <Icon as={InfoIcon} ml={2} color={helperTextColor} w={4} h={4} cursor="help" />
            </Tooltip>
          </FormLabel>
          <RadioGroup
            value={formData.discountType}
            onChange={value => onChange('discountType', value)}
          >
            <Stack direction="row" spacing={5}>
              {getDiscountOptions().map(option => (
                <Box
                  key={option.value}
                  bg={radioBg}
                  borderWidth="1px"
                  borderColor={formData.discountType === option.value ? 'primary.500' : borderColor}
                  borderRadius="md"
                  px={4}
                  py={3}
                  cursor="pointer"
                  _hover={{ borderColor: 'primary.500' }}
                >
                  <Radio
                    value={option.value}
                    colorScheme="primary"
                    spacing={3}
                  >
                    {option.label}
                  </Radio>
                </Box>
              ))}
            </Stack>
          </RadioGroup>
          <FormHelperText color={helperTextColor}>
            {formData.discountType === 'percentage'
              ? 'Percentage will be taken off the total cart amount'
              : 'Fixed amount will be deducted from the total cart'}
          </FormHelperText>
        </FormControl>

        <FormControl>
          <FormLabel fontWeight="medium">
            {formData.discountType === 'percentage' ? 'Discount Percentage' : 'Discount Amount'}
            <Tooltip
              label={formData.discountType === 'percentage'
                ? 'Enter the percentage to discount from the cart total'
                : 'Enter the fixed amount to discount from the cart total'}
              placement="top"
              hasArrow
            >
              <Icon as={InfoIcon} ml={2} color={helperTextColor} w={4} h={4} cursor="help" />
            </Tooltip>
          </FormLabel>
          <InputGroup>
            <InputLeftAddon
              children={formData.discountType === 'percentage' ? '%' : '$'}
              bg={useColorModeValue('gray.50', 'gray.700')}
              borderColor={borderColor}
            />
            <NumberInput
              value={formData.discountValue}
              onChange={value => onChange('discountValue', parseFloat(value) || 0)}
              min={0}
              max={formData.discountType === 'percentage' ? 100 : undefined}
              precision={formData.discountType === 'percentage' ? 0 : 2}
              step={formData.discountType === 'percentage' ? 1 : 0.01}
              w="full"
            >
              <NumberInputField
                borderLeftRadius={0}
                borderColor={borderColor}
                _hover={{ borderColor: 'primary.500' }}
                _focus={{
                  borderColor: 'primary.500',
                  boxShadow: '0 0 0 1px var(--chakra-colors-primary-500)'
                }}
              />
              <NumberInputStepper>
                <NumberIncrementStepper
                  borderColor={borderColor}
                  color={helperTextColor}
                />
                <NumberDecrementStepper
                  borderColor={borderColor}
                  color={helperTextColor}
                />
              </NumberInputStepper>
            </NumberInput>
          </InputGroup>
          <FormHelperText color={helperTextColor}>
            {formData.discountType === 'percentage'
              ? `${formData.discountValue}% will be deducted from qualifying orders`
              : `$${formData.discountValue} will be deducted from qualifying orders`}
          </FormHelperText>
        </FormControl>

        <Box
          mt={4}
          p={4}
          bg={useColorModeValue('primary.50', 'gray.700')}
          borderRadius="md"
          borderWidth="1px"
          borderColor={useColorModeValue('primary.100', 'gray.600')}
        >
          <Text fontSize="sm" color={helperTextColor}>
            <Icon as={InfoIcon} mr={2} color="primary.500" w={4} h={4} />
            {formData.discountType === 'percentage'
              ? 'Percentage discounts are calculated based on the cart total'
              : 'Fixed amount discounts are deducted from the final cart total'}
          </Text>
        </Box>

        <FormControl>
          <FormLabel fontWeight="medium">
            Celebration Effect
            <Tooltip
              label="Choose a celebration animation when customer reaches the discount threshold"
              placement="top"
              hasArrow
            >
              <Icon as={InfoIcon} ml={2} color={helperTextColor} w={4} h={4} cursor="help" />
            </Tooltip>
          </FormLabel>

          <RadioGroup
            value={formData.celebrationType}
            onChange={handleCelebrationTypeChange}
          >
            <Stack>
              {confettiStyles.map((style) => (
                <Radio
                  key={style.id}
                  value={style.id}
                  bg={radioBg}
                  _hover={{ bg: bgHover }}
                >
                  {style.label}
                </Radio>
              ))}
            </Stack>
          </RadioGroup>

          <FormHelperText color={helperTextColor}>
            Select how to celebrate when customers unlock this discount
          </FormHelperText>
        </FormControl>

        {formData.celebrationType !== 'none' && (
          <FormControl>
            <HStack justify="space-between" align="center">
              <FormLabel fontWeight="medium" mb={0}>
                Preview Celebration
              </FormLabel>
              <Button
                size="sm"
                colorScheme="primary"
                onClick={triggerPreview}
              >
                Show Preview
              </Button>
            </HStack>
            <FormHelperText color={helperTextColor}>
              Click to preview how the celebration will look
            </FormHelperText>
          </FormControl>
        )}
      </VStack>
    </Box>
  );
};

export default DiscountSettings;