import {
  Box,
  VStack,
  Text,
  Heading,
  Divider,
  ButtonGroup,
  IconButton,
  Tooltip,
  useColorModeValue,
  Flex,
  Badge,
  Icon,
} from '@chakra-ui/react';
import { MdDesktopWindows, MdPhoneAndroid } from 'react-icons/md';
import { formatCurrency } from '../../../utils/formatters';
import { useState, forwardRef } from 'react';

const DesktopIcon = forwardRef((props, ref) => (
  <Icon as={MdDesktopWindows} ref={ref} {...props} />
));

const MobileIcon = forwardRef((props, ref) => (
  <Icon as={MdPhoneAndroid} ref={ref} {...props} />
));

DesktopIcon.displayName = 'DesktopIcon';
MobileIcon.displayName = 'MobileIcon';

const Preview = ({ formData, progressStyles, successStyles }) => {
  const [device, setDevice] = useState('desktop');
  const bgColor = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.600');
  const headerBg = useColorModeValue('gray.50', 'gray.700');

  const getPreviewMessage = (template) => {
    const discount = formData.discountType === 'percentage'
      ? `${formData.discountValue}%`
      : formatCurrency(formData.discountValue);

    const remaining = formData.conditionType === 'cart_total'
      ? formatCurrency(formData.conditionValue)
      : formData.conditionValue;

    return template
      .replace('{discount}', discount)
      .replace('{remaining_amount}', remaining);
  };

  const getMessageStyle = (styles) => {
    const transform = [];
    if (styles.scaleX || styles.scaleY) {
      transform.push(`scale(${styles.scaleX || 1}, ${styles.scaleY || 1})`);
    }
    if (styles.rotate) {
      transform.push(`rotate(${styles.rotate}deg)`);
    }
    if (styles.translateX || styles.translateY) {
      transform.push(`translate(${styles.translateX || 0}px, ${styles.translateY || 0}px)`);
    }
    if (styles.skewX || styles.skewY) {
      transform.push(`skew(${styles.skewX || 0}deg, ${styles.skewY || 0}deg)`);
    }

    // Handle filters
    const filter = [];
    if (styles.blur) {
      filter.push(`blur(${styles.blur}px)`);
    }
    if (styles.brightness && styles.brightness !== 100) {
      filter.push(`brightness(${styles.brightness}%)`);
    }
    if (styles.contrast && styles.contrast !== 100) {
      filter.push(`contrast(${styles.contrast}%)`);
    }
    if (styles.saturation && styles.saturation !== 100) {
      filter.push(`saturate(${styles.saturation}%)`);
    }
    if (styles.hue) {
      filter.push(`hue-rotate(${styles.hue}deg)`);
    }
    if (styles.opacity && styles.opacity !== 100) {
      filter.push(`opacity(${styles.opacity}%)`);
    }

    // Handle backdrop filters
    const backdropFilter = [];
    if (styles.backdropBlur) {
      backdropFilter.push(`blur(${styles.backdropBlur}px)`);
    }
    if (styles.backdropBrightness && styles.backdropBrightness !== 100) {
      backdropFilter.push(`brightness(${styles.backdropBrightness}%)`);
    }
    if (styles.backdropContrast && styles.backdropContrast !== 100) {
      backdropFilter.push(`contrast(${styles.backdropContrast}%)`);
    }
    if (styles.backdropSaturation && styles.backdropSaturation !== 100) {
      backdropFilter.push(`saturate(${styles.backdropSaturation}%)`);
    }
    if (styles.backdropOpacity && styles.backdropOpacity !== 100) {
      backdropFilter.push(`opacity(${styles.backdropOpacity}%)`);
    }

    // Handle mix blend mode with validation
    const validBlendModes = [
      'normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten',
      'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference',
      'exclusion', 'hue', 'saturation', 'color', 'luminosity'
    ];
    const mixBlendMode = validBlendModes.includes(styles.mixBlendMode)
      ? styles.mixBlendMode
      : 'normal';

    return {
      backgroundColor: styles.backgroundColor || '#ffffff',
      color: styles.textColor || '#000000',
      borderColor: styles.borderColor || '#e2e8f0',
      borderWidth: `${styles.borderWidth || 1}px`,
      borderStyle: styles.borderStyle || 'solid',
      borderRadius: `${styles.borderRadius || 4}px`,
      padding: `${styles.padding || 16}px`,
      paddingTop: `${styles.paddingTop || styles.padding || 16}px`,
      paddingRight: `${styles.paddingRight || styles.padding || 16}px`,
      paddingBottom: `${styles.paddingBottom || styles.padding || 16}px`,
      paddingLeft: `${styles.paddingLeft || styles.padding || 16}px`,
      margin: '0',
      fontSize: `${styles.fontSize || 16}px`,
      fontWeight: styles.fontWeight || 'normal',
      lineHeight: styles.lineHeight || 1.5,
      textAlign: styles.textAlign || 'left',
      letterSpacing: `${styles.letterSpacing || 0}px`,
      textDecoration: styles.textDecoration || 'none',
      textTransform: styles.textTransform || 'none',
      boxShadow: styles.boxShadowX !== undefined
        ? `${styles.boxShadowX || 0}px ${styles.boxShadowY || 0}px ${styles.boxShadowBlur || 0}px ${styles.boxShadowSpread || 0}px ${styles.boxShadowColor || 'rgba(0,0,0,0.1)'}`
        : 'none',
      textShadow: styles.textShadowX !== undefined
        ? `${styles.textShadowX || 0}px ${styles.textShadowY || 0}px ${styles.textShadowBlur || 0}px ${styles.textShadowColor || 'rgba(0,0,0,0.1)'}`
        : 'none',
      transform: transform.length ? transform.join(' ') : 'none',
      transformOrigin: styles.transformOrigin || 'center',
      filter: filter.length ? filter.join(' ') : 'none',
      backdropFilter: backdropFilter.length ? backdropFilter.join(' ') : 'none',
      mixBlendMode,
      isolation: mixBlendMode !== 'normal' ? 'isolate' : 'auto',
      '--bg-opacity': styles.backgroundOpacity || 1,
      '--text-opacity': styles.textOpacity || 1,
      backgroundColor: `rgba(${hexToRgb(styles.backgroundColor || '#ffffff')}, var(--bg-opacity))`,
      color: `rgba(${hexToRgb(styles.textColor || '#000000')}, var(--text-opacity))`,
    };
  };

  // Helper function to convert hex to rgb
  const hexToRgb = (hex) => {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result
      ? `${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)}`
      : '0, 0, 0';
  };

  const getDeviceWrapper = (children) => {
    if (device === 'mobile') {
      return (
        <Box
          maxW="375px"
          mx="auto"
          borderRadius="xl"
          overflow="hidden"
          boxShadow="lg"
          bg={bgColor}
        >
          <Box
            bg={headerBg}
            p={4}
            borderBottom="1px solid"
            borderColor={borderColor}
          >
            <Box
              w="40%"
              h="4px"
              bg={borderColor}
              borderRadius="full"
              mx="auto"
            />
          </Box>
          <Box p={4}>
            {children}
          </Box>
        </Box>
      );
    }
    return (
      <Box
        w="100%"
        borderRadius="xl"
        overflow="hidden"
        boxShadow="lg"
        bg={bgColor}
      >
        <Box
          bg={headerBg}
          p={4}
          borderBottom="1px solid"
          borderColor={borderColor}
        >
          <Box
            w="40px"
            h="4px"
            bg={borderColor}
            borderRadius="full"
            ml="auto"
          />
        </Box>
        <Box p={6}>
          {children}
        </Box>
      </Box>
    );
  };

  return (
    <VStack spacing={6} align="stretch">
      <Box>
        <Flex justify="space-between" align="center" mb={4}>
          <Box>
            <Heading size="md" mb={1}>Message Preview</Heading>
            <Text fontSize="sm" color="gray.500">
              This is how your messages will appear to customers
            </Text>
          </Box>
          <ButtonGroup
            size="sm"
            isAttached
            variant="outline"
            bg={bgColor}
            borderRadius="md"
            p={1}
          >
            <Tooltip label="Desktop view" hasArrow>
              <IconButton
                icon={<DesktopIcon />}
                aria-label="Desktop view"
                onClick={() => setDevice('desktop')}
                colorScheme={device === 'desktop' ? 'primary' : 'gray'}
                variant={device === 'desktop' ? 'solid' : 'ghost'}
                borderRadius="md"
              />
            </Tooltip>
            <Tooltip label="Mobile view" hasArrow>
              <IconButton
                icon={<MobileIcon />}
                aria-label="Mobile view"
                onClick={() => setDevice('mobile')}
                colorScheme={device === 'mobile' ? 'primary' : 'gray'}
                variant={device === 'mobile' ? 'solid' : 'ghost'}
                borderRadius="md"
              />
            </Tooltip>
          </ButtonGroup>
        </Flex>
      </Box>

      {getDeviceWrapper(
        <VStack spacing={6} align="stretch">
          <Box>
            <Flex align="center" gap={2} mb={3}>
              <Text fontWeight="medium" color="gray.700">Progress Message</Text>
              <Badge colorScheme="primary" variant="subtle">Current State</Badge>
            </Flex>
            <Box
              style={getMessageStyle(progressStyles)}
              boxShadow="sm"
              transition="all 0.3s"
              _hover={{ boxShadow: 'md', transform: 'translateY(-1px)' }}
              role="button"
              cursor="pointer"
              position="relative"
              animation="fadeIn 0.3s ease-in-out"
              borderRadius="md"
            >
              {getPreviewMessage(formData.progressMessage)}
            </Box>
          </Box>

          <Divider />

          <Box opacity={0.6} transition="opacity 0.3s" _hover={{ opacity: 1 }}>
            <Flex align="center" gap={2} mb={3}>
              <Text fontWeight="medium" color="gray.700">Success Message</Text>
              <Badge colorScheme="gray" variant="subtle">Future State</Badge>
            </Flex>
            <Box
              style={getMessageStyle(successStyles)}
              boxShadow="sm"
              transition="all 0.3s"
              _hover={{ boxShadow: 'md', transform: 'translateY(-1px)' }}
              role="button"
              cursor="pointer"
              borderRadius="md"
            >
              {getPreviewMessage(formData.successMessage)}
            </Box>
          </Box>
        </VStack>
      )}

      <style>{`
        @keyframes fadeIn {
          from { opacity: 0; transform: translateY(10px); }
          to { opacity: 1; transform: translateY(0); }
        }
      `}</style>
    </VStack>
  );
};

export default Preview;