import React, { useState } from 'react';
import {
  Box,
  VStack,
  HStack,
  Text,
  Tabs,
  TabList,
  TabPanels,
  Tab,
  TabPanel,
  FormControl,
  FormLabel,
  Input,
  Slider,
  SliderTrack,
  SliderFilledTrack,
  SliderThumb,
  Select,
  Switch,
  NumberInput,
  NumberInputField,
  NumberInputStepper,
  NumberIncrementStepper,
  NumberDecrementStepper,
  IconButton,
  Divider,
  Button,
  useColorModeValue,
} from '@chakra-ui/react';
import { FiType, FiLayout, FiBox, FiDroplet, FiGrid, FiSmartphone, FiBarChart2, FiSidebar, FiCode, FiColumns, FiExternalLink } from 'react-icons/fi';
import { FaRegNewspaper, FaRegSquare, FaColumns } from 'react-icons/fa';
import CustomCSSEditor from './CustomCSSEditor';
import ColumnLayoutManager from './ColumnLayoutManager';
import ContextualAdminLinks from './ContextualAdminLinks';
import { useClubTheme } from '../../contexts/ClubThemeContext';

interface VisualStylePanelProps {
  elementName: string;
  onStyleChange: (styles: Record<string, any>) => void;
  currentStyles?: Record<string, any>;
}

const VisualStylePanel: React.FC<VisualStylePanelProps> = ({
  elementName,
  onStyleChange,
  currentStyles = {},
}) => {
  const bgColor = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.600');
  const clubTheme = useClubTheme();
  const primaryColor = clubTheme.primary || '#0b5cff';

  const [styles, setStyles] = useState({
    // Typography
    fontFamily: currentStyles.fontFamily || 'Inter',
    fontSize: currentStyles.fontSize || 16,
    fontWeight: currentStyles.fontWeight || 400,
    lineHeight: currentStyles.lineHeight || 1.5,
    letterSpacing: currentStyles.letterSpacing || 0,
    textTransform: currentStyles.textTransform || 'none',
    
    // Colors
    color: currentStyles.color || '#000000',
    backgroundColor: currentStyles.backgroundColor || '#ffffff',
    
    // Spacing
    paddingTop: currentStyles.paddingTop || 0,
    paddingRight: currentStyles.paddingRight || 0,
    paddingBottom: currentStyles.paddingBottom || 0,
    paddingLeft: currentStyles.paddingLeft || 0,
    marginTop: currentStyles.marginTop || 0,
    marginRight: currentStyles.marginRight || 0,
    marginBottom: currentStyles.marginBottom || 0,
    marginLeft: currentStyles.marginLeft || 0,
    
    // Layout
    width: currentStyles.width || 'auto',
    height: currentStyles.height || 'auto',
    display: currentStyles.display || 'block',
    
    // Grid Layout
    gridTemplateColumns: currentStyles.gridTemplateColumns || 'repeat(3, 1fr)',
    gridTemplateRows: currentStyles.gridTemplateRows || 'auto',
    gridColumnGap: currentStyles.gridColumnGap || 16,
    gridRowGap: currentStyles.gridRowGap || 16,
    gridAutoFlow: currentStyles.gridAutoFlow || 'row',
    alignItems: currentStyles.alignItems || 'stretch',
    justifyItems: currentStyles.justifyItems || 'stretch',
    
    // Custom CSS
    customCSS: currentStyles.customCSS || '',
    
    ...currentStyles,
  });

  const updateStyle = (key: string, value: any) => {
    const newStyles = { ...styles, [key]: value };
    setStyles(newStyles);
    onStyleChange(newStyles);
  };

  return (
    <Box
      width="280px"
      bg={bgColor}
      borderRight="1px"
      borderColor={primaryColor}
      height="100vh"
      overflowY="auto"
      pt="60px"
    >
      <Tabs size="sm" colorScheme="blue">
        <TabList px={2} flexWrap="wrap">
          <Tab><FiType /> <Text ml={1}>Content</Text></Tab>
          <Tab><FiLayout /> <Text ml={1}>Style</Text></Tab>
          <Tab><FiColumns /> <Text ml={1}>Layout</Text></Tab>
          <Tab><FiCode /> <Text ml={1}>CSS</Text></Tab>
          <Tab><FiExternalLink /> <Text ml={1}>Admin</Text></Tab>
        </TabList>

        <TabPanels>
          {/* Content Tab */}
          <TabPanel>
            <VStack align="stretch" spacing={4}>
              <Text fontWeight="bold" fontSize="sm" textTransform="uppercase" color="gray.500">
                Typography
              </Text>

              {/* Font Family */}
              <FormControl>
                <FormLabel fontSize="xs">Font Family</FormLabel>
                <Select
                  size="sm"
                  value={styles.fontFamily}
                  onChange={(e) => updateStyle('fontFamily', e.target.value)}
                >
                  <option value="Inter">Inter</option>
                  <option value="Roboto">Roboto</option>
                  <option value="Open Sans">Open Sans</option>
                  <option value="Lato">Lato</option>
                  <option value="Montserrat">Montserrat</option>
                  <option value="Poppins">Poppins</option>
                  <option value="Georgia">Georgia</option>
                  <option value="Times New Roman">Times New Roman</option>
                </Select>
              </FormControl>

              {/* Font Size */}
              <FormControl>
                <FormLabel fontSize="xs">Size (px)</FormLabel>
                <HStack>
                  <NumberInput
                    size="sm"
                    value={styles.fontSize}
                    min={8}
                    max={128}
                    onChange={(_, val) => updateStyle('fontSize', val)}
                    flex={1}
                  >
                    <NumberInputField />
                    <NumberInputStepper>
                      <NumberIncrementStepper />
                      <NumberDecrementStepper />
                    </NumberInputStepper>
                  </NumberInput>
                </HStack>
              </FormControl>

              {/* Font Weight */}
              <FormControl>
                <FormLabel fontSize="xs">Weight</FormLabel>
                <HStack spacing={2}>
                  <Slider
                    value={styles.fontWeight}
                    min={100}
                    max={900}
                    step={100}
                    onChange={(val) => updateStyle('fontWeight', val)}
                    flex={1}
                  >
                    <SliderTrack>
                      <SliderFilledTrack bg={primaryColor} />
                    </SliderTrack>
                    <SliderThumb />
                  </Slider>
                  <Text fontSize="xs" minW="40px">{styles.fontWeight}</Text>
                </HStack>
              </FormControl>

              {/* Line Height */}
              <FormControl>
                <FormLabel fontSize="xs">Line Height</FormLabel>
                <HStack spacing={2}>
                  <Slider
                    value={styles.lineHeight}
                    min={0.5}
                    max={3}
                    step={0.1}
                    onChange={(val) => updateStyle('lineHeight', val)}
                    flex={1}
                  >
                    <SliderTrack>
                      <SliderFilledTrack bg={primaryColor} />
                    </SliderTrack>
                    <SliderThumb />
                  </Slider>
                  <Text fontSize="xs" minW="40px">{styles.lineHeight.toFixed(1)}</Text>
                </HStack>
              </FormControl>

              {/* Letter Spacing */}
              <FormControl>
                <FormLabel fontSize="xs">Letter Spacing (px)</FormLabel>
                <HStack spacing={2}>
                  <Slider
                    value={styles.letterSpacing}
                    min={-5}
                    max={10}
                    step={0.1}
                    onChange={(val) => updateStyle('letterSpacing', val)}
                    flex={1}
                  >
                    <SliderTrack>
                      <SliderFilledTrack bg={primaryColor} />
                    </SliderTrack>
                    <SliderThumb />
                  </Slider>
                  <Text fontSize="xs" minW="40px">{styles.letterSpacing.toFixed(1)}</Text>
                </HStack>
              </FormControl>

              {/* Text Transform */}
              <FormControl>
                <FormLabel fontSize="xs">Transform</FormLabel>
                <Select
                  size="sm"
                  value={styles.textTransform}
                  onChange={(e) => updateStyle('textTransform', e.target.value)}
                >
                  <option value="none">None</option>
                  <option value="uppercase">UPPERCASE</option>
                  <option value="lowercase">lowercase</option>
                  <option value="capitalize">Capitalize</option>
                </Select>
              </FormControl>
            </VStack>
          </TabPanel>

          {/* Style Tab */}
          <TabPanel>
            <VStack align="stretch" spacing={4}>
              <Text fontWeight="bold" fontSize="sm" textTransform="uppercase" color="gray.500">
                Colors
              </Text>

              {/* Text Color */}
              <FormControl>
                <FormLabel fontSize="xs">Text Color</FormLabel>
                <HStack>
                  <Input
                    type="color"
                    value={styles.color}
                    onChange={(e) => updateStyle('color', e.target.value)}
                    size="sm"
                    w="60px"
                    p={1}
                  />
                  <Input
                    value={styles.color}
                    onChange={(e) => updateStyle('color', e.target.value)}
                    size="sm"
                    placeholder="#000000"
                  />
                </HStack>
              </FormControl>

              {/* Background Color */}
              <FormControl>
                <FormLabel fontSize="xs">Background Color</FormLabel>
                <HStack>
                  <Input
                    type="color"
                    value={styles.backgroundColor}
                    onChange={(e) => updateStyle('backgroundColor', e.target.value)}
                    size="sm"
                    w="60px"
                    p={1}
                  />
                  <Input
                    value={styles.backgroundColor}
                    onChange={(e) => updateStyle('backgroundColor', e.target.value)}
                    size="sm"
                    placeholder="#ffffff"
                  />
                </HStack>
              </FormControl>

              <Divider my={2} />

              <Text fontWeight="bold" fontSize="sm" textTransform="uppercase" color="gray.500">
                Spacing
              </Text>

              {/* Padding */}
              <FormControl>
                <FormLabel fontSize="xs">Padding (px)</FormLabel>
                <VStack spacing={2}>
                  <HStack width="100%">
                    <Text fontSize="xs" minW="20px">T</Text>
                    <NumberInput
                      size="xs"
                      value={styles.paddingTop}
                      min={0}
                      onChange={(_, val) => updateStyle('paddingTop', val)}
                      flex={1}
                    >
                      <NumberInputField />
                    </NumberInput>
                  </HStack>
                  <HStack width="100%">
                    <Text fontSize="xs" minW="20px">R</Text>
                    <NumberInput
                      size="xs"
                      value={styles.paddingRight}
                      min={0}
                      onChange={(_, val) => updateStyle('paddingRight', val)}
                      flex={1}
                    >
                      <NumberInputField />
                    </NumberInput>
                  </HStack>
                  <HStack width="100%">
                    <Text fontSize="xs" minW="20px">B</Text>
                    <NumberInput
                      size="xs"
                      value={styles.paddingBottom}
                      min={0}
                      onChange={(_, val) => updateStyle('paddingBottom', val)}
                      flex={1}
                    >
                      <NumberInputField />
                    </NumberInput>
                  </HStack>
                  <HStack width="100%">
                    <Text fontSize="xs" minW="20px">L</Text>
                    <NumberInput
                      size="xs"
                      value={styles.paddingLeft}
                      min={0}
                      onChange={(_, val) => updateStyle('paddingLeft', val)}
                      flex={1}
                    >
                      <NumberInputField />
                    </NumberInput>
                  </HStack>
                </VStack>
              </FormControl>

              {/* Margin */}
              <FormControl>
                <FormLabel fontSize="xs">Margin (px)</FormLabel>
                <VStack spacing={2}>
                  <HStack width="100%">
                    <Text fontSize="xs" minW="20px">T</Text>
                    <NumberInput
                      size="xs"
                      value={styles.marginTop}
                      onChange={(_, val) => updateStyle('marginTop', val)}
                      flex={1}
                    >
                      <NumberInputField />
                    </NumberInput>
                  </HStack>
                  <HStack width="100%">
                    <Text fontSize="xs" minW="20px">R</Text>
                    <NumberInput
                      size="xs"
                      value={styles.marginRight}
                      onChange={(_, val) => updateStyle('marginRight', val)}
                      flex={1}
                    >
                      <NumberInputField />
                    </NumberInput>
                  </HStack>
                  <HStack width="100%">
                    <Text fontSize="xs" minW="20px">B</Text>
                    <NumberInput
                      size="xs"
                      value={styles.marginBottom}
                      onChange={(_, val) => updateStyle('marginBottom', val)}
                      flex={1}
                    >
                      <NumberInputField />
                    </NumberInput>
                  </HStack>
                  <HStack width="100%">
                    <Text fontSize="xs" minW="20px">L</Text>
                    <NumberInput
                      size="xs"
                      value={styles.marginLeft}
                      onChange={(_, val) => updateStyle('marginLeft', val)}
                      flex={1}
                    >
                      <NumberInputField />
                    </NumberInput>
                  </HStack>
                </VStack>
              </FormControl>
            </VStack>
          </TabPanel>

          {/* Layout Tab (was Grid Tab) */}
          <TabPanel>
            <VStack align="stretch" spacing={4}>
              <Text fontWeight="bold" fontSize="sm" textTransform="uppercase" color="gray.500">
                Grid Layout
              </Text>

              {/* Enable Grid */}
              <FormControl display="flex" alignItems="center">
                <FormLabel fontSize="xs" mb={0} flex={1}>Enable Grid Layout</FormLabel>
                <Switch
                  size="sm"
                  isChecked={styles.display === 'grid'}
                  onChange={(e) => updateStyle('display', e.target.checked ? 'grid' : 'block')}
                  sx={{
                    'span[data-checked]': {
                      bg: primaryColor,
                      borderColor: primaryColor,
                    }
                  }}
                />
              </FormControl>

              {styles.display === 'grid' && (
                <>
                  <Divider />

                  {/* Quick Templates */}
                  <FormControl>
                    <FormLabel fontSize="xs" fontWeight="bold">Quick Templates</FormLabel>
                    <VStack spacing={2}>
                      <Button
                        size="xs"
                        width="100%"
                        variant="outline"
                        onClick={() => updateStyle('gridTemplateColumns', '1fr')}
                        justifyContent="flex-start"
                      >
                        <HStack spacing={2}>
                          <FiSmartphone />
                          <Text>Single Column</Text>
                        </HStack>
                      </Button>
                      <Button
                        size="xs"
                        width="100%"
                        variant="outline"
                        onClick={() => updateStyle('gridTemplateColumns', '1fr 1fr')}
                        justifyContent="flex-start"
                      >
                        <HStack spacing={2}>
                          <FaColumns />
                          <Text>Two Equal (50% / 50%)</Text>
                        </HStack>
                      </Button>
                      <Button
                        size="xs"
                        width="100%"
                        variant="outline"
                        onClick={() => updateStyle('gridTemplateColumns', '2fr 1fr')}
                        justifyContent="flex-start"
                      >
                        <HStack spacing={2}>
                          <FiBarChart2 />
                          <Text>Left Larger (66% / 33%)</Text>
                        </HStack>
                      </Button>
                      <Button
                        size="xs"
                        width="100%"
                        variant="outline"
                        onClick={() => updateStyle('gridTemplateColumns', '1fr 2fr')}
                        justifyContent="flex-start"
                      >
                        <HStack spacing={2}>
                          <FiBarChart2 style={{ transform: 'scaleX(-1)' }} />
                          <Text>Right Larger (33% / 66%)</Text>
                        </HStack>
                      </Button>
                      <Button
                        size="xs"
                        width="100%"
                        variant="outline"
                        onClick={() => updateStyle('gridTemplateColumns', '1fr 1fr 1fr')}
                        justifyContent="flex-start"
                      >
                        <HStack spacing={2}>
                          <FiGrid />
                          <Text>Three Equal (33% / 33% / 33%)</Text>
                        </HStack>
                      </Button>
                      <Button
                        size="xs"
                        width="100%"
                        variant="outline"
                        onClick={() => updateStyle('gridTemplateColumns', '2fr 1fr 1fr')}
                        justifyContent="flex-start"
                      >
                        <HStack spacing={2}>
                          <FaRegNewspaper />
                          <Text>Featured + Two (50% / 25% / 25%)</Text>
                        </HStack>
                      </Button>
                      <Button
                        size="xs"
                        width="100%"
                        variant="outline"
                        onClick={() => updateStyle('gridTemplateColumns', 'repeat(4, 1fr)')}
                        justifyContent="flex-start"
                      >
                        <HStack spacing={2}>
                          <FaRegSquare />
                          <Text>Four Equal (25% each)</Text>
                        </HStack>
                      </Button>
                      <Button
                        size="xs"
                        width="100%"
                        variant="outline"
                        onClick={() => updateStyle('gridTemplateColumns', '3fr 1fr')}
                        justifyContent="flex-start"
                      >
                        <HStack spacing={2}>
                          <FiSidebar />
                          <Text>Main + Sidebar (75% / 25%)</Text>
                        </HStack>
                      </Button>
                    </VStack>
                  </FormControl>

                  <Divider />

                  {/* Custom Columns */}
                  <FormControl>
                    <FormLabel fontSize="xs">Grid Template Columns</FormLabel>
                    <Input
                      size="sm"
                      value={styles.gridTemplateColumns}
                      onChange={(e) => updateStyle('gridTemplateColumns', e.target.value)}
                      placeholder="e.g. 1fr 2fr or 300px 1fr"
                      fontFamily="monospace"
                      fontSize="xs"
                    />
                    <Text fontSize="10px" color="gray.500" mt={1}>
                      Examples: 1fr 1fr | 2fr 1fr | 200px 1fr | repeat(3, 1fr)
                    </Text>
                  </FormControl>

                  {/* Grid Template Rows */}
                  <FormControl>
                    <FormLabel fontSize="xs">Grid Template Rows</FormLabel>
                    <Input
                      size="sm"
                      value={styles.gridTemplateRows}
                      onChange={(e) => updateStyle('gridTemplateRows', e.target.value)}
                      placeholder="auto or 200px 1fr"
                      fontFamily="monospace"
                      fontSize="xs"
                    />
                  </FormControl>

                  {/* Column Gap */}
                  <FormControl>
                    <FormLabel fontSize="xs">Column Gap (px)</FormLabel>
                    <HStack spacing={2}>
                      <Slider
                        value={styles.gridColumnGap}
                        min={0}
                        max={100}
                        step={4}
                        onChange={(val) => updateStyle('gridColumnGap', val)}
                        flex={1}
                      >
                        <SliderTrack>
                          <SliderFilledTrack bg="purple.500" />
                        </SliderTrack>
                        <SliderThumb />
                      </Slider>
                      <Text fontSize="xs" minW="40px">{styles.gridColumnGap}px</Text>
                    </HStack>
                  </FormControl>

                  {/* Row Gap */}
                  <FormControl>
                    <FormLabel fontSize="xs">Row Gap (px)</FormLabel>
                    <HStack spacing={2}>
                      <Slider
                        value={styles.gridRowGap}
                        min={0}
                        max={100}
                        step={4}
                        onChange={(val) => updateStyle('gridRowGap', val)}
                        flex={1}
                      >
                        <SliderTrack>
                          <SliderFilledTrack bg="purple.500" />
                        </SliderTrack>
                        <SliderThumb />
                      </Slider>
                      <Text fontSize="xs" minW="40px">{styles.gridRowGap}px</Text>
                    </HStack>
                  </FormControl>

                  <Divider />

                  {/* Grid Auto Flow */}
                  <FormControl>
                    <FormLabel fontSize="xs">Auto Flow</FormLabel>
                    <Select
                      size="sm"
                      value={styles.gridAutoFlow}
                      onChange={(e) => updateStyle('gridAutoFlow', e.target.value)}
                    >
                      <option value="row">Row (horizontal)</option>
                      <option value="column">Column (vertical)</option>
                      <option value="row dense">Row Dense</option>
                      <option value="column dense">Column Dense</option>
                    </Select>
                  </FormControl>

                  {/* Align Items */}
                  <FormControl>
                    <FormLabel fontSize="xs">Align Items (vertical)</FormLabel>
                    <Select
                      size="sm"
                      value={styles.alignItems}
                      onChange={(e) => updateStyle('alignItems', e.target.value)}
                    >
                      <option value="stretch">Stretch</option>
                      <option value="start">Start</option>
                      <option value="center">Center</option>
                      <option value="end">End</option>
                      <option value="baseline">Baseline</option>
                    </Select>
                  </FormControl>

                  {/* Justify Items */}
                  <FormControl>
                    <FormLabel fontSize="xs">Justify Items (horizontal)</FormLabel>
                    <Select
                      size="sm"
                      value={styles.justifyItems}
                      onChange={(e) => updateStyle('justifyItems', e.target.value)}
                    >
                      <option value="stretch">Stretch</option>
                      <option value="start">Start</option>
                      <option value="center">Center</option>
                      <option value="end">End</option>
                    </Select>
                  </FormControl>
                </>
              )}
            </VStack>
          </TabPanel>

          {/* Custom CSS Tab */}
          <TabPanel p={0}>
            <CustomCSSEditor
              elementName={elementName}
              onCSSChange={(css) => updateStyle('customCSS', css)}
              currentCSS={styles.customCSS || ''}
            />
          </TabPanel>

          {/* Admin Links Tab */}
          <TabPanel>
            <ContextualAdminLinks elementName={elementName} />
          </TabPanel>
        </TabPanels>
      </Tabs>
    </Box>
  );
};

export default VisualStylePanel;
