import React, { useState, useEffect, useRef } from 'react';
import {
  Box,
  IconButton,
  HStack,
  Popover,
  PopoverTrigger,
  PopoverContent,
  PopoverBody,
  Button,
  VStack,
  Input,
  useColorModeValue,
  Tooltip,
} from '@chakra-ui/react';
import { FiBold, FiItalic, FiUnderline, FiType, FiLink, FiCheck, FiX } from 'react-icons/fi';

interface InlineTextEditorProps {
  elementId: string;
  onSave: (content: string) => void;
  initialContent?: string;
}

const InlineTextEditor: React.FC<InlineTextEditorProps> = ({ elementId, onSave, initialContent = '' }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [content, setContent] = useState(initialContent);
  const [showLinkPopover, setShowLinkPopover] = useState(false);
  const [linkUrl, setLinkUrl] = useState('');
  const editorRef = useRef<HTMLDivElement>(null);
  const bgColor = useColorModeValue('white', 'gray.800');

  useEffect(() => {
    if (isEditing && editorRef.current) {
      editorRef.current.focus();
      // Select all text
      const selection = window.getSelection();
      const range = document.createRange();
      range.selectNodeContents(editorRef.current);
      selection?.removeAllRanges();
      selection?.addRange(range);
    }
  }, [isEditing]);

  const handleFormat = (command: string, value?: string) => {
    document.execCommand(command, false, value);
  };

  const handleSave = () => {
    if (editorRef.current) {
      const newContent = editorRef.current.innerHTML;
      setContent(newContent);
      onSave(newContent);
      setIsEditing(false);
    }
  };

  const handleCancel = () => {
    if (editorRef.current) {
      editorRef.current.innerHTML = content;
    }
    setIsEditing(false);
  };

  const handleInsertLink = () => {
    if (linkUrl) {
      handleFormat('createLink', linkUrl);
      setLinkUrl('');
      setShowLinkPopover(false);
    }
  };

  return (
    <Box position="relative">
      {isEditing && (
        <Box
          position="absolute"
          top="-50px"
          left="0"
          bg={bgColor}
          borderRadius="md"
          boxShadow="lg"
          p={2}
          zIndex={10000}
          border="1px solid"
          borderColor="blue.400"
        >
          <HStack spacing={1}>
            <Tooltip label="Bold">
              <IconButton
                aria-label="Bold"
                icon={<FiBold />}
                size="sm"
                variant="ghost"
                onClick={() => handleFormat('bold')}
              />
            </Tooltip>
            <Tooltip label="Italic">
              <IconButton
                aria-label="Italic"
                icon={<FiItalic />}
                size="sm"
                variant="ghost"
                onClick={() => handleFormat('italic')}
              />
            </Tooltip>
            <Tooltip label="Underline">
              <IconButton
                aria-label="Underline"
                icon={<FiUnderline />}
                size="sm"
                variant="ghost"
                onClick={() => handleFormat('underline')}
              />
            </Tooltip>
            
            <Popover isOpen={showLinkPopover} onClose={() => setShowLinkPopover(false)}>
              <PopoverTrigger>
                <IconButton
                  aria-label="Link"
                  icon={<FiLink />}
                  size="sm"
                  variant="ghost"
                  onClick={() => setShowLinkPopover(true)}
                />
              </PopoverTrigger>
              <PopoverContent width="250px">
                <PopoverBody>
                  <VStack spacing={2}>
                    <Input
                      placeholder="https://example.com"
                      value={linkUrl}
                      onChange={(e) => setLinkUrl(e.target.value)}
                      size="sm"
                    />
                    <HStack width="100%">
                      <Button size="sm" colorScheme="blue" onClick={handleInsertLink} flex={1}>
                        Insert
                      </Button>
                      <Button size="sm" variant="ghost" onClick={() => setShowLinkPopover(false)}>
                        Cancel
                      </Button>
                    </HStack>
                  </VStack>
                </PopoverBody>
              </PopoverContent>
            </Popover>

            <Box width="1px" height="20px" bg="gray.300" mx={1} />
            
            <Tooltip label="Save">
              <IconButton
                aria-label="Save"
                icon={<FiCheck />}
                size="sm"
                colorScheme="green"
                onClick={handleSave}
              />
            </Tooltip>
            <Tooltip label="Cancel">
              <IconButton
                aria-label="Cancel"
                icon={<FiX />}
                size="sm"
                colorScheme="red"
                variant="ghost"
                onClick={handleCancel}
              />
            </Tooltip>
          </HStack>
        </Box>
      )}
      
      <Box
        ref={editorRef}
        contentEditable={isEditing}
        suppressContentEditableWarning
        dangerouslySetInnerHTML={{ __html: content }}
        onClick={() => !isEditing && setIsEditing(true)}
        onBlur={(e) => {
          // Don't close if clicking on toolbar
          if (!e.relatedTarget || !(e.relatedTarget as HTMLElement).closest('[role="group"]')) {
            // Auto-save on blur if changed
            if (editorRef.current && editorRef.current.innerHTML !== content) {
              handleSave();
            }
          }
        }}
        cursor={isEditing ? 'text' : 'pointer'}
        outline={isEditing ? '2px solid' : 'none'}
        outlineColor="blue.400"
        outlineOffset="2px"
        p={isEditing ? 2 : 0}
        borderRadius="md"
        transition="all 0.2s"
        _hover={{
          outline: isEditing ? '2px solid' : '2px dashed',
          outlineColor: 'blue.400',
        }}
      />
    </Box>
  );
};

export default InlineTextEditor;
