import React, { useState, useEffect } from 'react';
import {
  Box,
  Flex,
  IconButton,
  VStack,
  HStack,
  Text,
  Select,
  Button,
  useToast,
  Tooltip,
  Badge,
  Collapse,
  useDisclosure,
  Drawer,
  DrawerBody,
  DrawerHeader,
  DrawerOverlay,
  DrawerContent,
  DrawerCloseButton,
  FormControl,
  FormLabel,
  Switch,
  Divider,
} from '@chakra-ui/react';
import { FiEdit, FiSave, FiX, FiEye, FiEyeOff, FiSettings } from 'react-icons/fi';
import { 
  PageElementConfig, 
  getPageElementConfigs, 
  batchUpdatePageElementConfigs,
  ELEMENT_VARIANTS 
} from '../../services/pageElements';
import { useAuth } from '../../contexts/AuthContext';

interface VisualPageEditorProps {
  pageType: string; // e.g., 'homepage', 'about'
  onConfigChange?: (configs: PageElementConfig[]) => void;
}

const VisualPageEditor: React.FC<VisualPageEditorProps> = ({ pageType, onConfigChange }) => {
  const { user } = useAuth();
  const isAdmin = user?.role === 'admin';
  const [isEditing, setIsEditing] = useState(false);
  const [configs, setConfigs] = useState<PageElementConfig[]>([]);
  const [localChanges, setLocalChanges] = useState<Record<string, string>>({});
  const [hasChanges, setHasChanges] = useState(false);
  const [isVisible, setIsVisible] = useState(true);
  const { isOpen, onOpen, onClose } = useDisclosure();
  const toast = useToast();

  // Load configurations
  useEffect(() => {
    if (!isAdmin) return;
    
    const loadConfigs = async () => {
      try {
        const data = await getPageElementConfigs(pageType);
        setConfigs(data);
        
        // Initialize local changes from existing configs
        const changes: Record<string, string> = {};
        data.forEach(cfg => {
          changes[cfg.element_name] = cfg.variant;
        });
        setLocalChanges(changes);
      } catch (error) {
        console.error('Failed to load page element configs:', error);
      }
    };

    loadConfigs();
  }, [pageType, isAdmin]);

  // Notify parent of config changes
  useEffect(() => {
    if (onConfigChange) {
      onConfigChange(configs);
    }
  }, [configs, onConfigChange]);

  const handleVariantChange = (elementName: string, variant: string) => {
    setLocalChanges(prev => ({
      ...prev,
      [elementName]: variant,
    }));
    setHasChanges(true);
  };

  const handleSave = async () => {
    try {
      // Build configs array from local changes
      const configsToSave: PageElementConfig[] = Object.entries(localChanges).map(([elementName, variant]) => ({
        page_type: pageType,
        element_name: elementName,
        variant,
      }));

      const result = await batchUpdatePageElementConfigs(configsToSave);
      
      toast({
        title: 'Changes saved',
        description: `Updated ${result.updated} configs, created ${result.created} new`,
        status: 'success',
        duration: 3000,
        isClosable: true,
      });

      // Reload configs
      const updated = await getPageElementConfigs(pageType);
      setConfigs(updated);
      setHasChanges(false);
      
      // Reload the page to apply changes
      window.location.reload();
    } catch (error) {
      toast({
        title: 'Failed to save changes',
        description: 'An error occurred while saving',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    }
  };

  const handleCancel = () => {
    // Reset local changes to match configs
    const changes: Record<string, string> = {};
    configs.forEach(cfg => {
      changes[cfg.element_name] = cfg.variant;
    });
    setLocalChanges(changes);
    setHasChanges(false);
    setIsEditing(false);
  };

  if (!isAdmin) return null;

  return (
    <>
      {/* Floating control button */}
      <Box
        position="fixed"
        right={4}
        bottom={20}
        zIndex={9999}
        display={isVisible ? 'block' : 'none'}
      >
        <Tooltip label="Visual Page Editor" hasArrow placement="left">
          <IconButton
            aria-label="Open visual editor"
            icon={<FiSettings />}
            colorScheme="purple"
            size="lg"
            borderRadius="full"
            boxShadow="lg"
            onClick={onOpen}
            _hover={{ transform: 'scale(1.1)' }}
            transition="all 0.2s"
          />
        </Tooltip>
      </Box>

      {/* Editor Drawer */}
      <Drawer isOpen={isOpen} placement="right" onClose={onClose} size="md">
        <DrawerOverlay />
        <DrawerContent>
          <DrawerCloseButton />
          <DrawerHeader borderBottomWidth="1px">
            <VStack align="stretch" spacing={2}>
              <HStack justify="space-between">
                <Text>Visual Page Editor</Text>
                <Badge colorScheme="purple">Admin</Badge>
              </HStack>
              <Text fontSize="sm" fontWeight="normal" color="gray.500">
                Configure visual variants for page elements
              </Text>
            </VStack>
          </DrawerHeader>

          <DrawerBody>
            <VStack align="stretch" spacing={6} py={4}>
              {/* Editor Status */}
              <Flex justify="space-between" align="center">
                <Text fontSize="sm" color="gray.600">
                  Page: <strong>{pageType}</strong>
                </Text>
                <HStack>
                  <Switch
                    size="sm"
                    isChecked={isEditing}
                    onChange={(e) => setIsEditing(e.target.checked)}
                  />
                  <Text fontSize="sm" fontWeight="bold">
                    {isEditing ? 'Editing' : 'Preview'}
                  </Text>
                </HStack>
              </Flex>

              <Divider />

              {/* Element Controls */}
              {Object.entries(ELEMENT_VARIANTS).map(([elementName, variants]) => (
                <Box key={elementName}>
                  <FormControl>
                    <FormLabel fontSize="sm" fontWeight="bold" textTransform="capitalize">
                      {elementName}
                    </FormLabel>
                    <Select
                      value={localChanges[elementName] || variants[0].value}
                      onChange={(e) => handleVariantChange(elementName, e.target.value)}
                      size="md"
                      isDisabled={!isEditing}
                    >
                      {variants.map((variant) => (
                        <option key={variant.value} value={variant.value}>
                          {variant.label} - {variant.description}
                        </option>
                      ))}
                    </Select>
                    
                    {/* Show current variant info */}
                    {localChanges[elementName] && (
                      <Text fontSize="xs" color="gray.500" mt={1}>
                        Current: {variants.find(v => v.value === localChanges[elementName])?.description || localChanges[elementName]}
                      </Text>
                    )}
                  </FormControl>
                </Box>
              ))}

              <Divider />

              {/* Action Buttons */}
              <VStack spacing={3}>
                {hasChanges && (
                  <Badge colorScheme="orange" fontSize="sm" p={2} borderRadius="md" w="full" textAlign="center">
                    You have unsaved changes
                  </Badge>
                )}
                
                <HStack spacing={2} w="full">
                  <Button
                    leftIcon={<FiSave />}
                    colorScheme="green"
                    onClick={handleSave}
                    isDisabled={!hasChanges || !isEditing}
                    flex={1}
                  >
                    Save & Reload
                  </Button>
                  <Button
                    leftIcon={<FiX />}
                    variant="outline"
                    onClick={handleCancel}
                    isDisabled={!hasChanges}
                    flex={1}
                  >
                    Cancel
                  </Button>
                </HStack>

                <Button
                  size="sm"
                  variant="ghost"
                  onClick={() => setIsVisible(!isVisible)}
                  leftIcon={isVisible ? <FiEyeOff /> : <FiEye />}
                  w="full"
                >
                  {isVisible ? 'Hide' : 'Show'} Editor Button
                </Button>
              </VStack>

              {/* Help Text */}
              <Box bg="blue.50" p={3} borderRadius="md" fontSize="sm">
                <Text fontWeight="bold" mb={1}>How to use:</Text>
                <VStack align="stretch" spacing={1} fontSize="xs">
                  <Text>1. Toggle editing mode ON</Text>
                  <Text>2. Select variants for each element</Text>
                  <Text>3. Click "Save & Reload" to apply</Text>
                  <Text>4. Page will reload with new styles</Text>
                </VStack>
              </Box>
            </VStack>
          </DrawerBody>
        </DrawerContent>
      </Drawer>
    </>
  );
};

export default VisualPageEditor;
