import React, { useState } from 'react';
import {
  Box,
  IconButton,
  Tooltip,
  Divider,
  Paper,
  ClickAwayListener,
} from '@mui/material';
import {
  Add,
  TrendingUp,
  Straighten,
  TextFields,
  Delete,
  Undo,
  Redo,
  ZoomIn,
  ZoomOut,
  LinearScale,
  Brush,
  CropFree,
  KeyboardArrowDown,
  SquareFoot,
  Timeline,
  Search,
  ShowChart,
  ChangeHistory,
  RadioButtonUnchecked,
  RotateRight,
  ViewWeek,
} from '@mui/icons-material';

// 도구 타입 정의
export type ChartTool = 
  | 'crosshair'
  | 'magnifier'
  | 'trendLine'
  | 'horizontalLine'
  | 'verticalLine'
  | 'rectangle'
  | 'fibonacci'
  | 'fibonacciTimezone'
  | 'fibonacciFan'
  | 'fibonacciCircle'
  | 'fibonacciWedge'
  | 'text'
  | 'brush'
  | 'measure'
  | 'diagonalLine'
  | 'angleLine'
  | 'parallelChannel';

interface ChartToolbarProps {
  activeTool: ChartTool | null;
  onToolChange: (tool: ChartTool) => void;
  onZoomIn?: () => void;
  onZoomOut?: () => void;
  onUndo?: () => void;
  onRedo?: () => void;
  onClearAll?: () => void;
  mode?: 'basic' | 'grid' | 'clean';
  onModeChange?: (mode: 'basic' | 'grid' | 'clean') => void;
}

// 개별 도구 정의
interface ToolItem {
  id: ChartTool;
  icon: React.ReactNode;
  label: string;
  hasSubmenu?: boolean;
}

const ChartToolbar: React.FC<ChartToolbarProps> = ({
  activeTool,
  onToolChange,
  onZoomIn,
  onZoomOut,
  onUndo,
  onRedo,
  onClearAll,
  mode,
  onModeChange,
}) => {
  const [expandedTool, setExpandedTool] = useState<string | null>(null);

  // 도구 정의 (업비트 트레이딩뷰 스타일 - 가로 배치)
  const tools: ToolItem[] = [
    { id: 'crosshair', icon: <Add sx={{ fontSize: 18 }} />, label: '십자선' },
    { id: 'magnifier', icon: <Search sx={{ fontSize: 18 }} />, label: '돋보기' },
    { id: 'trendLine', icon: <TrendingUp sx={{ fontSize: 18 }} />, label: '추세선', hasSubmenu: true },
    { id: 'horizontalLine', icon: <Straighten sx={{ fontSize: 18 }} />, label: '수평선', hasSubmenu: true },
    { id: 'fibonacci', icon: <LinearScale sx={{ fontSize: 18 }} />, label: '피보나치', hasSubmenu: true },
    { id: 'rectangle', icon: <CropFree sx={{ fontSize: 18 }} />, label: '사각형' },
    { id: 'measure', icon: <Timeline sx={{ fontSize: 18 }} />, label: '기간 측정' },
    { id: 'brush', icon: <Brush sx={{ fontSize: 18 }} />, label: '브러시' },
    { id: 'text', icon: <TextFields sx={{ fontSize: 18 }} />, label: '텍스트' },
  ];

  // 하위 도구 메뉴 정의
  const subMenus: { [key: string]: ToolItem[] } = {
    trendLine: [
      { id: 'trendLine', icon: <TrendingUp sx={{ fontSize: 16 }} />, label: '추세선' },
      { id: 'diagonalLine', icon: <ShowChart sx={{ fontSize: 16, transform: 'rotate(45deg)' }} />, label: '대각선' },
      { id: 'angleLine', icon: <RotateRight sx={{ fontSize: 16 }} />, label: '각도선' },
      { id: 'parallelChannel', icon: <Timeline sx={{ fontSize: 16 }} />, label: '평행채널' },
    ],
    horizontalLine: [
      { id: 'horizontalLine', icon: <Straighten sx={{ fontSize: 16 }} />, label: '수평선' },
      { id: 'verticalLine', icon: <Straighten sx={{ fontSize: 16, transform: 'rotate(90deg)' }} />, label: '수직선' },
    ],
    fibonacci: [
      { id: 'fibonacci', icon: <LinearScale sx={{ fontSize: 16 }} />, label: '피보나치 되돌림' },
      { id: 'fibonacciTimezone', icon: <ViewWeek sx={{ fontSize: 16 }} />, label: '피보나치 타임존' },
      { id: 'fibonacciFan', icon: <ChangeHistory sx={{ fontSize: 16 }} />, label: '피보나치 팬' },
      { id: 'fibonacciCircle', icon: <RadioButtonUnchecked sx={{ fontSize: 16 }} />, label: '피보나치 서클' },
      { id: 'fibonacciWedge', icon: <ShowChart sx={{ fontSize: 16 }} />, label: '피보나치 웻지' },
    ],
  };

  const handleToolClick = (tool: ToolItem) => {
    if (tool.hasSubmenu) {
      setExpandedTool(expandedTool === tool.id ? null : tool.id);
    } else {
      onToolChange(tool.id);
      setExpandedTool(null);
    }
  };

  const handleSubToolSelect = (toolId: ChartTool) => {
    onToolChange(toolId);
    setExpandedTool(null);
  };

  return (
    <Paper
      elevation={0}
      sx={{
        backgroundColor: 'background.paper',
        borderRadius: 0,
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        gap: 0,
        px: 0.5,
        py: 0.25,
        borderBottom: 1,
        borderColor: 'divider',
        boxShadow: 1,
      }}
    >
      {/* 도구 버튼들 */}
      {tools.map((tool) => (
        <Box key={tool.id} sx={{ position: 'relative' }}>
          <Tooltip title={tool.label} placement="bottom" arrow>
            <Box
              onClick={() => handleToolClick(tool)}
              sx={{
                display: 'flex',
                alignItems: 'center',
                gap: 0,
                px: 0.75,
                py: 0.5,
                cursor: 'pointer',
                borderRadius: 0.5,
                color: activeTool === tool.id ? 'primary.main' : 'text.secondary',
                backgroundColor: activeTool === tool.id ? 'action.selected' : 'transparent',
                '&:hover': {
                  backgroundColor: 'action.hover',
                  color: 'primary.main',
                },
                height: 28,
              }}
            >
              {tool.icon}
              {tool.hasSubmenu && <KeyboardArrowDown sx={{ fontSize: 14, ml: -0.25 }} />}
            </Box>
          </Tooltip>
          
          {/* 하위 메뉴 */}
          {tool.hasSubmenu && expandedTool === tool.id && subMenus[tool.id] && (
            <ClickAwayListener onClickAway={() => setExpandedTool(null)}>
              <Paper
                elevation={8}
                sx={{
                  position: 'absolute',
                  left: 0,
                  top: '100%',
                  mt: 0.5,
                  backgroundColor: 'background.paper',
                  borderRadius: 1,
                  overflow: 'hidden',
                  minWidth: 120,
                  zIndex: 1000,
                  border: 1,
                  borderColor: 'divider',
                }}
              >
                {subMenus[tool.id].map((subTool) => (
                  <Box
                    key={subTool.id}
                    onClick={() => handleSubToolSelect(subTool.id)}
                    sx={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: 1,
                      px: 1.5,
                      py: 0.75,
                      cursor: 'pointer',
                      color: activeTool === subTool.id ? 'primary.main' : 'text.secondary',
                      backgroundColor: activeTool === subTool.id ? 'action.selected' : 'transparent',
                      '&:hover': {
                        backgroundColor: 'action.hover',
                        color: 'primary.main',
                      },
                      fontSize: '12px',
                    }}
                  >
                    {subTool.icon}
                    <span>{subTool.label}</span>
                  </Box>
                ))}
              </Paper>
            </ClickAwayListener>
          )}
        </Box>
      ))}

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

      {/* 줌 컨트롤 */}
      <Tooltip title="확대" placement="bottom" arrow>
        <IconButton size="small" onClick={onZoomIn} sx={iconButtonStyle}>
          <ZoomIn sx={{ fontSize: 18 }} />
        </IconButton>
      </Tooltip>
      
      <Tooltip title="축소" placement="bottom" arrow>
        <IconButton size="small" onClick={onZoomOut} sx={iconButtonStyle}>
          <ZoomOut sx={{ fontSize: 18 }} />
        </IconButton>
      </Tooltip>

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

      {/* 실행 취소/다시 실행 */}
      <Tooltip title="실행 취소" placement="bottom" arrow>
        <IconButton size="small" onClick={onUndo} sx={iconButtonStyle}>
          <Undo sx={{ fontSize: 18 }} />
        </IconButton>
      </Tooltip>
      
      <Tooltip title="다시 실행" placement="bottom" arrow>
        <IconButton size="small" onClick={onRedo} sx={iconButtonStyle}>
          <Redo sx={{ fontSize: 18 }} />
        </IconButton>
      </Tooltip>

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

      {/* 모두 지우기 */}
      <Tooltip title="모두 지우기" placement="bottom" arrow>
        <IconButton 
          size="small" 
          onClick={onClearAll} 
          sx={{
            ...iconButtonStyle,
            '&:hover': {
              backgroundColor: 'rgba(244, 67, 54, 0.1)',
              color: '#f44336',
            },
          }}
        >
          <Delete sx={{ fontSize: 18 }} />
        </IconButton>
      </Tooltip>
    </Paper>
  );
};

// 공통 아이콘 버튼 스타일
const iconButtonStyle = {
  width: 28,
  height: 28,
  borderRadius: 0.5,
  color: 'text.secondary',
  '&:hover': {
    backgroundColor: 'action.hover',
    color: 'primary.main',
  },
};

export default ChartToolbar;

