import React, { useState } from 'react';
import {
  Box,
  IconButton,
  Select,
  MenuItem,
  Popover,
  Tooltip,
  Divider,
  ClickAwayListener,
} from '@mui/material';
import {
  DragIndicator,
  Palette,
  Settings,
  Delete,
  Visibility,
  VisibilityOff,
  Lock,
  LockOpen,
} from '@mui/icons-material';
import { FibonacciTimezoneSettings } from './FibonacciTimezoneDialog';

interface FibonacciToolbarProps {
  open: boolean;
  anchorPosition: { top: number; left: number } | null;
  settings: FibonacciTimezoneSettings;
  onClose: () => void;
  onColorChange: (color: string) => void;
  onLineWidthChange: (width: number) => void;
  onLineStyleChange: (style: 'solid' | 'dashed' | 'dotted') => void;
  onSettingsClick: () => void;
  onDelete: () => void;
  onVisibilityToggle: () => void;
  isVisible: boolean;
}

const FibonacciToolbar: React.FC<FibonacciToolbarProps> = ({
  open,
  anchorPosition,
  settings,
  onClose,
  onColorChange,
  onLineWidthChange,
  onLineStyleChange,
  onSettingsClick,
  onDelete,
  onVisibilityToggle,
  isVisible,
}) => {
  const [colorPickerAnchor, setColorPickerAnchor] = useState<HTMLElement | null>(null);
  const [isDragging, setIsDragging] = useState(false);
  const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });

  // 색상 팔레트
  const colorPalette = [
    ['#000000', '#434651', '#666666', '#999999', '#B2B5BE', '#D1D4DC', '#E1E3EB', '#F0F3FA'],
    ['#F23645', '#FF9800', '#FDD835', '#26A69A', '#00BCD4', '#2196F3', '#3F51B5', '#9C27B0'],
    ['#880E4F', '#B71C1C', '#E65100', '#F57F17', '#827717', '#33691E', '#1B5E20', '#004D40'],
  ];

  const handleColorPickerOpen = (event: React.MouseEvent<HTMLElement>) => {
    setColorPickerAnchor(event.currentTarget);
  };

  const handleColorPickerClose = () => {
    setColorPickerAnchor(null);
  };

  const handleMouseDown = (e: React.MouseEvent) => {
    setIsDragging(true);
    if (anchorPosition) {
      setDragOffset({
        x: e.clientX - anchorPosition.left,
        y: e.clientY - anchorPosition.top,
      });
    }
  };

  if (!open || !anchorPosition) return null;

  return (
    <>
      <ClickAwayListener
        onClickAway={(event) => {
          // 색상 팔레트 팝오버가 열려있으면 무시
          if (colorPickerAnchor) return;
          onClose();
        }}
      >
        <Box
          sx={{
            position: 'fixed',
            top: anchorPosition.top,
            left: anchorPosition.left,
            zIndex: 1300,
            bgcolor: 'background.paper',
            boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
            borderRadius: 1,
            border: '1px solid',
            borderColor: 'divider',
            display: 'flex',
            alignItems: 'center',
            gap: 0.5,
            px: 1,
            py: 0.5,
          }}
        >
        {/* 드래그 핸들 */}
        <Box
          onMouseDown={handleMouseDown}
          sx={{
            cursor: 'move',
            display: 'flex',
            alignItems: 'center',
            px: 0.5,
            '&:hover': {
              bgcolor: 'action.hover',
            },
          }}
        >
          <DragIndicator sx={{ fontSize: 18, color: 'text.secondary' }} />
        </Box>

        <Divider orientation="vertical" flexItem sx={{ mx: 0.5 }} />

        {/* 템플릿 */}
        <Tooltip title="템플릿">
          <Select
            size="small"
            value="default"
            sx={{
              minWidth: 80,
              height: 28,
              fontSize: '12px',
              '.MuiOutlinedInput-notchedOutline': { border: 'none' },
            }}
          >
            <MenuItem value="default">기본</MenuItem>
            <MenuItem value="custom1">커스텀 1</MenuItem>
            <MenuItem value="custom2">커스텀 2</MenuItem>
          </Select>
        </Tooltip>

        <Divider orientation="vertical" flexItem sx={{ mx: 0.5 }} />

        {/* 색상 선택 */}
        <Tooltip title="색상">
          <IconButton
            size="small"
            onClick={handleColorPickerOpen}
            sx={{
              width: 28,
              height: 28,
              bgcolor: settings.baseline?.color || '#2196F3',
              border: '2px solid',
              borderColor: 'divider',
              '&:hover': {
                opacity: 0.8,
              },
            }}
          >
            <Palette sx={{ fontSize: 0, color: 'transparent' }} />
          </IconButton>
        </Tooltip>

        {/* 선 굵기 */}
        <Tooltip title="선 굵기">
          <Select
            size="small"
            value={settings.baseline?.lineWidth || 2}
            onChange={(e) => onLineWidthChange(Number(e.target.value))}
            sx={{
              minWidth: 50,
              height: 28,
              fontSize: '12px',
              '.MuiOutlinedInput-notchedOutline': { border: 'none' },
            }}
          >
            <MenuItem value={1}>1</MenuItem>
            <MenuItem value={2}>2</MenuItem>
            <MenuItem value={3}>3</MenuItem>
            <MenuItem value={4}>4</MenuItem>
          </Select>
        </Tooltip>

        {/* 선 유형 */}
        <Tooltip title="선 유형">
          <Select
            size="small"
            value={settings.baseline?.lineStyle || 'solid'}
            onChange={(e) => onLineStyleChange(e.target.value as any)}
            sx={{
              minWidth: 70,
              height: 28,
              fontSize: '12px',
              '.MuiOutlinedInput-notchedOutline': { border: 'none' },
            }}
          >
            <MenuItem value="solid">실선</MenuItem>
            <MenuItem value="dashed">점선</MenuItem>
            <MenuItem value="dotted">대시선</MenuItem>
          </Select>
        </Tooltip>

        <Divider orientation="vertical" flexItem sx={{ mx: 0.5 }} />

        {/* 보이기/숨기기 */}
        <Tooltip title={isVisible ? '숨기기' : '보이기'}>
          <IconButton size="small" onClick={onVisibilityToggle} sx={{ width: 28, height: 28 }}>
            {isVisible ? (
              <Visibility sx={{ fontSize: 18 }} />
            ) : (
              <VisibilityOff sx={{ fontSize: 18 }} />
            )}
          </IconButton>
        </Tooltip>

        {/* 설정 */}
        <Tooltip title="설정">
          <IconButton size="small" onClick={onSettingsClick} sx={{ width: 28, height: 28 }}>
            <Settings sx={{ fontSize: 18 }} />
          </IconButton>
        </Tooltip>

        {/* 삭제 */}
        <Tooltip title="삭제">
          <IconButton
            size="small"
            onClick={() => {
              if (window.confirm('이 피보나치 타임존을 삭제하시겠습니까?')) {
                onDelete();
                onClose();
              }
            }}
            sx={{ width: 28, height: 28, color: 'error.main' }}
          >
            <Delete sx={{ fontSize: 18 }} />
          </IconButton>
        </Tooltip>
      </Box>
      </ClickAwayListener>

      {/* 색상 팔레트 팝오버 */}
      <Popover
        open={Boolean(colorPickerAnchor)}
        anchorEl={colorPickerAnchor}
        onClose={handleColorPickerClose}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
      >
        <Box sx={{ p: 2, width: 240 }}>
          {colorPalette.map((row, rowIndex) => (
            <Box key={rowIndex} sx={{ display: 'flex', gap: 0.5, mb: 0.5 }}>
              {row.map((color, colIndex) => (
                <Box
                  key={colIndex}
                  onClick={() => {
                    onColorChange(color);
                    handleColorPickerClose();
                  }}
                  sx={{
                    width: 24,
                    height: 24,
                    bgcolor: color,
                    cursor: 'pointer',
                    border: '1px solid rgba(0,0,0,0.1)',
                    '&:hover': {
                      border: '2px solid white',
                      boxShadow: '0 0 4px rgba(0,0,0,0.3)',
                    },
                  }}
                />
              ))}
            </Box>
          ))}
        </Box>
      </Popover>
    </>
  );
};

export default FibonacciToolbar;
