import React, { useState, useEffect } from 'react';
import {
  Box,
  VStack,
  HStack,
  Text,
  Textarea,
  Button,
  IconButton,
  useToast,
  Tabs,
  TabList,
  Tab,
  TabPanels,
  TabPanel,
  Code,
  Alert,
  AlertIcon,
  useColorModeValue,
  Divider,
} from '@chakra-ui/react';
import { FiCode, FiEye, FiSave, FiRefreshCw } from 'react-icons/fi';

interface CustomCSSEditorProps {
  elementName: string;
  onCSSChange: (css: string) => void;
  currentCSS?: string;
}

const CustomCSSEditor: React.FC<CustomCSSEditorProps> = ({
  elementName,
  onCSSChange,
  currentCSS = '',
}) => {
  const [css, setCSS] = useState(currentCSS);
  const [isValid, setIsValid] = useState(true);
  const [preview, setPreview] = useState(false);
  const toast = useToast();
  const bgColor = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.600');

  useEffect(() => {
    setCSS(currentCSS);
  }, [currentCSS]);

  const validateCSS = (cssString: string): boolean => {
    try {
      // Basic CSS validation
      if (!cssString.trim()) return true;
      
      // Check for balanced braces
      const openBraces = (cssString.match(/{/g) || []).length;
      const closeBraces = (cssString.match(/}/g) || []).length;
      
      return openBraces === closeBraces;
    } catch {
      return false;
    }
  };

  const handleCSSChange = (value: string) => {
    setCSS(value);
    const valid = validateCSS(value);
    setIsValid(valid);
    
    if (valid && preview) {
      applyCSS(value);
    }
  };

  const applyCSS = (cssString: string) => {
    // Remove existing custom style
    const existingStyle = document.getElementById(`custom-css-${elementName}`);
    if (existingStyle) {
      existingStyle.remove();
    }

    if (cssString.trim()) {
      // Create new style element
      const style = document.createElement('style');
      style.id = `custom-css-${elementName}`;
      style.textContent = `
        [data-element="${elementName}"] {
          ${cssString}
        }
      `;
      document.head.appendChild(style);
    }
  };

  const handleSave = () => {
    if (!isValid) {
      toast({
        title: 'Invalid CSS',
        description: 'Please fix CSS errors before saving',
        status: 'error',
        duration: 3000,
      });
      return;
    }

    applyCSS(css);
    onCSSChange(css);
    
    toast({
      title: 'CSS Applied',
      description: 'Custom styles have been applied',
      status: 'success',
      duration: 2000,
    });
  };

  const handleReset = () => {
    setCSS('');
    const existingStyle = document.getElementById(`custom-css-${elementName}`);
    if (existingStyle) {
      existingStyle.remove();
    }
    onCSSChange('');
  };

  const cssExamples = [
    {
      label: 'Background Gradient',
      code: `background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;`,
    },
    {
      label: 'Shadow & Hover',
      code: `box-shadow: 0 10px 25px rgba(0,0,0,0.1);
transition: transform 0.3s;

&:hover {
  transform: translateY(-5px);
}`,
    },
    {
      label: 'Border Radius',
      code: `border-radius: 20px;
overflow: hidden;`,
    },
    {
      label: 'Animation',
      code: `animation: fadeIn 1s ease-in;

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}`,
    },
  ];

  return (
    <Box width="100%" height="100%">
      <Tabs size="sm" variant="enclosed" colorScheme="purple">
        <TabList>
          <Tab>
            <HStack spacing={2}>
              <FiCode />
              <Text>CSS Editor</Text>
            </HStack>
          </Tab>
          <Tab>
            <HStack spacing={2}>
              <FiEye />
              <Text>Examples</Text>
            </HStack>
          </Tab>
        </TabList>

        <TabPanels>
          {/* Editor Tab */}
          <TabPanel p={0}>
            <VStack align="stretch" spacing={3} p={4}>
              <HStack justify="space-between">
                <Text fontSize="xs" fontWeight="bold" color="gray.500" textTransform="uppercase">
                  Custom CSS for {elementName}
                </Text>
                <HStack spacing={2}>
                  <Button
                    size="xs"
                    leftIcon={<FiEye />}
                    variant={preview ? 'solid' : 'outline'}
                    colorScheme={preview ? 'blue' : 'gray'}
                    onClick={() => {
                      setPreview(!preview);
                      if (!preview && isValid) {
                        applyCSS(css);
                      }
                    }}
                  >
                    Preview
                  </Button>
                  <Button
                    size="xs"
                    leftIcon={<FiRefreshCw />}
                    variant="ghost"
                    onClick={handleReset}
                  >
                    Reset
                  </Button>
                </HStack>
              </HStack>

              {!isValid && (
                <Alert status="error" borderRadius="md" fontSize="sm">
                  <AlertIcon />
                  Invalid CSS syntax. Check for missing braces or semicolons.
                </Alert>
              )}

              <Textarea
                value={css}
                onChange={(e) => handleCSSChange(e.target.value)}
                placeholder={`/* Enter custom CSS properties */
background: #f0f0f0;
padding: 20px;
border-radius: 10px;`}
                fontFamily="monospace"
                fontSize="sm"
                minHeight="300px"
                bg={useColorModeValue('gray.50', 'gray.900')}
                borderColor={isValid ? borderColor : 'red.300'}
                _focus={{
                  borderColor: isValid ? 'purple.400' : 'red.400',
                  boxShadow: isValid ? '0 0 0 1px var(--chakra-colors-purple-400)' : '0 0 0 1px var(--chakra-colors-red-400)',
                }}
              />

              <Divider />

              <Alert status="info" borderRadius="md" fontSize="xs">
                <AlertIcon />
                <Box>
                  <Text fontWeight="bold">Pro tip:</Text>
                  <Text>Use standard CSS properties. Avoid selectors - styles apply to the element automatically.</Text>
                </Box>
              </Alert>

              <Button
                leftIcon={<FiSave />}
                colorScheme="purple"
                size="sm"
                onClick={handleSave}
                isDisabled={!isValid}
              >
                Apply CSS
              </Button>
            </VStack>
          </TabPanel>

          {/* Examples Tab */}
          <TabPanel>
            <VStack align="stretch" spacing={3} p={4}>
              <Text fontSize="xs" fontWeight="bold" color="gray.500" textTransform="uppercase">
                Quick CSS Examples
              </Text>
              
              {cssExamples.map((example, index) => (
                <Box
                  key={index}
                  p={3}
                  borderRadius="md"
                  border="1px"
                  borderColor={borderColor}
                  cursor="pointer"
                  transition="all 0.2s"
                  _hover={{
                    borderColor: 'purple.400',
                    transform: 'translateX(4px)',
                  }}
                  onClick={() => setCSS(example.code)}
                >
                  <Text fontWeight="bold" fontSize="sm" mb={2}>
                    {example.label}
                  </Text>
                  <Code
                    fontSize="xs"
                    display="block"
                    whiteSpace="pre"
                    p={2}
                    borderRadius="sm"
                    bg={useColorModeValue('gray.100', 'gray.900')}
                  >
                    {example.code}
                  </Code>
                </Box>
              ))}
            </VStack>
          </TabPanel>
        </TabPanels>
      </Tabs>
    </Box>
  );
};

export default CustomCSSEditor;
