import React, { useState } from 'react';
import {
  Box,
  VStack,
  HStack,
  IconButton,
  Button,
  Text,
  SimpleGrid,
  Tooltip,
  useColorModeValue,
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalCloseButton,
  useDisclosure,
} from '@chakra-ui/react';
import {
  FiPlus,
  FiColumns,
  FiGrid,
  FiLayout,
  FiTrash2,
} from 'react-icons/fi';
import { FaColumns, FaRegNewspaper, FaThLarge } from 'react-icons/fa';

interface Column {
  id: string;
  width: string;
  elements: string[];
}

interface ColumnLayoutManagerProps {
  elementName: string;
  onLayoutChange: (columns: Column[]) => void;
  currentColumns?: Column[];
}

const ColumnLayoutManager: React.FC<ColumnLayoutManagerProps> = ({
  elementName,
  onLayoutChange,
  currentColumns = [],
}) => {
  const [columns, setColumns] = useState<Column[]>(currentColumns);
  const { isOpen, onOpen, onClose } = useDisclosure();
  const bgColor = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.600');
  const hoverBg = useColorModeValue('gray.50', 'gray.700');

  const layoutTemplates = [
    {
      name: 'Single Column',
      icon: FiLayout,
      columns: [{ id: '1', width: '100%', elements: [] }],
    },
    {
      name: 'Two Equal',
      icon: FaColumns,
      columns: [
        { id: '1', width: '50%', elements: [] },
        { id: '2', width: '50%', elements: [] },
      ],
    },
    {
      name: 'Three Equal',
      icon: FiGrid,
      columns: [
        { id: '1', width: '33.33%', elements: [] },
        { id: '2', width: '33.33%', elements: [] },
        { id: '3', width: '33.33%', elements: [] },
      ],
    },
    {
      name: 'Four Equal',
      icon: FaThLarge,
      columns: [
        { id: '1', width: '25%', elements: [] },
        { id: '2', width: '25%', elements: [] },
        { id: '3', width: '25%', elements: [] },
        { id: '4', width: '25%', elements: [] },
      ],
    },
    {
      name: 'Left Sidebar',
      icon: FiColumns,
      columns: [
        { id: '1', width: '33.33%', elements: [] },
        { id: '2', width: '66.67%', elements: [] },
      ],
    },
    {
      name: 'Right Sidebar',
      icon: FiColumns,
      columns: [
        { id: '1', width: '66.67%', elements: [] },
        { id: '2', width: '33.33%', elements: [] },
      ],
    },
    {
      name: 'Featured + Two',
      icon: FaRegNewspaper,
      columns: [
        { id: '1', width: '50%', elements: [] },
        { id: '2', width: '25%', elements: [] },
        { id: '3', width: '25%', elements: [] },
      ],
    },
    {
      name: 'Three + One',
      icon: FiGrid,
      columns: [
        { id: '1', width: '75%', elements: [] },
        { id: '2', width: '25%', elements: [] },
      ],
    },
  ];

  const applyTemplate = (template: typeof layoutTemplates[0]) => {
    setColumns(template.columns);
    onLayoutChange(template.columns);
    onClose();
  };

  const addColumn = () => {
    const newColumn: Column = {
      id: `col-${Date.now()}`,
      width: `${100 / (columns.length + 1)}%`,
      elements: [],
    };
    
    // Recalculate existing column widths
    const newColumns = [
      ...columns.map(col => ({
        ...col,
        width: `${100 / (columns.length + 1)}%`,
      })),
      newColumn,
    ];
    
    setColumns(newColumns);
    onLayoutChange(newColumns);
  };

  const removeColumn = (columnId: string) => {
    const newColumns = columns.filter(col => col.id !== columnId);
    
    // Recalculate remaining column widths
    const equalWidth = `${100 / newColumns.length}%`;
    const updatedColumns = newColumns.map(col => ({
      ...col,
      width: equalWidth,
    }));
    
    setColumns(updatedColumns);
    onLayoutChange(updatedColumns);
  };

  return (
    <Box>
      <VStack align="stretch" spacing={3}>
        <HStack justify="space-between">
          <Text fontSize="xs" fontWeight="bold" color="gray.500" textTransform="uppercase">
            Column Layout
          </Text>
          <HStack spacing={2}>
            <Button
              size="xs"
              leftIcon={<FiColumns />}
              onClick={onOpen}
              variant="outline"
            >
              Templates
            </Button>
            <Tooltip label="Add Column">
              <IconButton
                aria-label="Add column"
                icon={<FiPlus />}
                size="xs"
                colorScheme="blue"
                onClick={addColumn}
                isDisabled={columns.length >= 6}
              />
            </Tooltip>
          </HStack>
        </HStack>

        {/* Current Columns Preview */}
        {columns.length > 0 && (
          <Box
            p={3}
            borderRadius="md"
            border="1px"
            borderColor={borderColor}
            bg={bgColor}
          >
            <HStack spacing={2} align="stretch">
              {columns.map((column, index) => (
                <Box
                  key={column.id}
                  flex={column.width}
                  p={2}
                  borderRadius="sm"
                  border="2px dashed"
                  borderColor="blue.300"
                  bg={hoverBg}
                  position="relative"
                  minHeight="80px"
                  display="flex"
                  flexDirection="column"
                  alignItems="center"
                  justifyContent="center"
                >
                  <Text fontSize="xs" fontWeight="bold" color="gray.500">
                    Column {index + 1}
                  </Text>
                  <Text fontSize="xs" color="gray.400">
                    {column.width}
                  </Text>
                  
                  {columns.length > 1 && (
                    <IconButton
                      aria-label="Remove column"
                      icon={<FiTrash2 />}
                      size="xs"
                      position="absolute"
                      top={1}
                      right={1}
                      variant="ghost"
                      colorScheme="red"
                      onClick={() => removeColumn(column.id)}
                    />
                  )}
                  
                  <Tooltip label="Click + to add element">
                    <IconButton
                      aria-label="Add element to column"
                      icon={<FiPlus />}
                      size="xs"
                      position="absolute"
                      bottom={1}
                      colorScheme="green"
                      variant="ghost"
                    />
                  </Tooltip>
                </Box>
              ))}
            </HStack>
          </Box>
        )}
      </VStack>

      {/* Layout Templates Modal */}
      <Modal isOpen={isOpen} onClose={onClose} size="xl">
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>Choose Column Layout</ModalHeader>
          <ModalCloseButton />
          <ModalBody pb={6}>
            <SimpleGrid columns={2} spacing={4}>
              {layoutTemplates.map((template, index) => (
                <Box
                  key={index}
                  p={4}
                  borderRadius="lg"
                  border="2px"
                  borderColor={borderColor}
                  cursor="pointer"
                  transition="all 0.2s"
                  _hover={{
                    borderColor: 'blue.400',
                    transform: 'translateY(-2px)',
                    boxShadow: 'md',
                  }}
                  onClick={() => applyTemplate(template)}
                >
                  <VStack spacing={3}>
                    <Box
                      as={template.icon}
                      fontSize="2xl"
                      color="blue.500"
                    />
                    <Text fontWeight="bold" fontSize="sm">
                      {template.name}
                    </Text>
                    
                    {/* Visual Preview */}
                    <HStack spacing={1} width="100%" height="40px">
                      {template.columns.map((col, i) => (
                        <Box
                          key={i}
                          flex={col.width}
                          bg="blue.100"
                          borderRadius="sm"
                          height="100%"
                        />
                      ))}
                    </HStack>
                  </VStack>
                </Box>
              ))}
            </SimpleGrid>
          </ModalBody>
        </ModalContent>
      </Modal>
    </Box>
  );
};

export default ColumnLayoutManager;
