import React from 'react';
import { MousePointer2, PencilLine, Hexagon, Square, Circle, Brush, Eraser, Combine, Scissors, FileUp, Trash2 } from 'lucide-react';
import { cn } from '../lib/utils';
import { AiSegmentationIcon } from './AiSegmentationIcon';
import { useStore } from '../store/useStore';

interface ToolsPaletteProps {
  activeTool: string;
  setActiveTool: (tool: string) => void;
  onTriggerAI?: () => void;
  onAutoPropagate?: () => void;
  onImportGtMask?: () => void;
  onDeleteMasks?: () => void;
  onClearMasks?: () => void;
  canAutoPropagate?: boolean;
  isPropagating?: boolean;
  canImportGtMask?: boolean;
  isImportingGtMask?: boolean;
}

export function ToolsPalette({
  activeTool,
  setActiveTool,
  onTriggerAI,
  onAutoPropagate,
  onImportGtMask,
  onDeleteMasks,
  onClearMasks,
  canAutoPropagate = false,
  isPropagating = false,
  canImportGtMask = false,
  isImportingGtMask = false,
}: ToolsPaletteProps) {
  const brushSize = useStore((state) => state.brushSize);
  const eraserSize = useStore((state) => state.eraserSize);
  const setBrushSize = useStore((state) => state.setBrushSize);
  const setEraserSize = useStore((state) => state.setEraserSize);
  const sizeControl = activeTool === 'brush'
    ? {
      label: '画笔大小',
      value: brushSize,
      min: 4,
      max: 96,
      onChange: setBrushSize,
    }
    : activeTool === 'eraser'
      ? {
        label: '橡皮擦大小',
        value: eraserSize,
        min: 4,
        max: 128,
        onChange: setEraserSize,
      }
      : null;
  const tools = [
    { id: 'move', icon: MousePointer2, label: '拖拽 / 选择 (V)' },
    { id: 'edit_polygon', icon: PencilLine, label: '调整多边形 (E)' },
    { id: 'create_polygon', icon: Hexagon, label: '创建多边形 (P)' },
    { id: 'create_rectangle', icon: Square, label: '创建矩形 (R)' },
    { id: 'create_circle', icon: Circle, label: '创建圆 (O)' },
    { id: 'brush', icon: Brush, label: '画笔 (B)' },
    { id: 'eraser', icon: Eraser, label: '橡皮擦 (X)' },
    { id: 'area_merge', icon: Combine, label: '区域合并 (+)' },
    { id: 'area_remove', icon: Scissors, label: '重叠区域去除 (-)' },
  ];

  return (
    <div className="h-full w-14 bg-[#0d0d0d] border-r border-white/5 flex flex-col items-start py-2 shrink-0 z-10 overflow-y-auto overflow-x-hidden overscroll-contain seg-scrollbar">
      <div className="flex flex-col gap-1.5 w-12 shrink-0 px-1.5">
        {tools.map(tool => {
          const Icon = tool.icon;
          const isActive = activeTool === tool.id;
          return (
            <React.Fragment key={tool.id}>
              <button
                onClick={() => setActiveTool(tool.id)}
                title={tool.label}
                className={cn(
                  "w-9 h-9 rounded-md flex items-center justify-center transition-all p-1.5",
                  isActive
                    ? (tool.id.includes('remove') ? "bg-red-500/10 text-red-500"
                      : tool.id.includes('merge') ? "bg-green-500/10 text-green-500"
                      : "bg-white/10 text-white")
                    : "text-gray-500 hover:bg-white/5 hover:text-white"
                )}
              >
                <Icon size={16} strokeWidth={isActive ? 2.5 : 2} />
              </button>
              {tool.id === 'eraser' && sizeControl && (
                <div className="w-9 rounded-md border border-white/10 bg-white/[0.03] px-1 py-2 text-center">
                  <label htmlFor={`${activeTool}-size`} className="sr-only">{sizeControl.label}</label>
                  <input
                    id={`${activeTool}-size`}
                    aria-label={sizeControl.label}
                    type="range"
                    min={sizeControl.min}
                    max={sizeControl.max}
                    value={sizeControl.value}
                    onChange={(event) => sizeControl.onChange(Number(event.target.value))}
                    className="h-20 w-7 accent-cyan-400 [writing-mode:vertical-rl]"
                  />
                  <div className="mt-1 text-[10px] leading-none text-gray-400">{sizeControl.value}</div>
                </div>
              )}
              {tool.id === 'eraser' && (
                <>
                  <button
                    type="button"
                    onClick={() => {
                      setActiveTool('auto_propagate');
                      onAutoPropagate?.();
                    }}
                    disabled={!canAutoPropagate || isPropagating}
                    aria-label="自动传播"
                    title={isPropagating ? '传播中...' : '自动传播'}
                    className={cn(
                      "w-9 h-9 rounded-md flex items-center justify-center transition-all p-1.5 border",
                      activeTool === 'auto_propagate'
                        ? "border-cyan-300/50 bg-cyan-500/20 text-white shadow-lg shadow-cyan-900/30"
                        : "border-cyan-500/25 bg-cyan-500/10 text-cyan-200 hover:bg-cyan-500/20 hover:text-white",
                      (!canAutoPropagate || isPropagating) && "opacity-35 cursor-not-allowed hover:bg-cyan-500/10 hover:text-cyan-200",
                    )}
                  >
                    <AiSegmentationIcon size={17} strokeWidth={2.2} />
                  </button>
                  <div className="my-1 h-px w-9 bg-white/15" />
                </>
              )}
              {tool.id === 'create_circle' && (
                <div className="my-1 h-px w-9 bg-white/15" />
              )}
            </React.Fragment>
          )
        })}

        <button
          onClick={onDeleteMasks}
          disabled={!onDeleteMasks}
          title="删除选中遮罩 (Del)"
          className="w-9 h-9 rounded-md flex items-center justify-center transition-all p-1.5 text-red-200 hover:bg-red-500/10 hover:text-red-100 disabled:opacity-35 disabled:cursor-not-allowed"
        >
          <span className="text-[10px] font-bold leading-none">DEL</span>
        </button>

        <button
          onClick={onClearMasks}
          disabled={!onClearMasks}
          title="清空遮罩"
          className="w-9 h-9 rounded-md flex items-center justify-center transition-all p-1.5 text-red-300 hover:bg-red-500/10 hover:text-red-200 disabled:opacity-35 disabled:cursor-not-allowed"
        >
          <Trash2 size={16} strokeWidth={2.1} />
        </button>

        <div data-testid="tool-group-separator" className="my-1 h-px w-9 bg-white/15" />

        <button
          onClick={onImportGtMask}
          disabled={!canImportGtMask || isImportingGtMask}
          title={isImportingGtMask ? '正在导入 GT Mask' : '导入 GT Mask'}
          className="w-9 h-9 rounded-md flex items-center justify-center transition-all p-1.5 border border-violet-500/30 bg-violet-500/10 text-violet-200 hover:bg-violet-500/20 hover:text-white disabled:opacity-35 disabled:hover:bg-violet-500/10 disabled:hover:text-violet-200 disabled:cursor-not-allowed"
        >
          <FileUp size={16} strokeWidth={2.2} />
        </button>

        <button
          onClick={() => {
            setActiveTool('sam_trigger');
            if (onTriggerAI) onTriggerAI();
          }}
          title="打开 AI 智能分割"
          className={cn(
             "w-9 h-9 rounded-md flex items-center justify-center transition-all",
             activeTool === 'sam_trigger'
              ? "bg-cyan-600 text-white shadow-lg shadow-cyan-900/20"
              : "text-gray-500 hover:bg-white/5"
          )}
        >
          <AiSegmentationIcon size={17} strokeWidth={2.1} />
        </button>

      </div>
    </div>
  );
}
