"use client";

import React, { useState, useRef, useEffect } from "react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";

// ============================================================================
// 类型定义
// ============================================================================

export interface AddRowMenuProps {
  /** 添加新行回调 */
  onAddRow: (rowType: 'separator', customText?: string) => void;
  /** 是否禁用 */
  disabled?: boolean;
  /** 自定义类名 */
  className?: string;
}

// ============================================================================
// 添加行菜单组件
// ============================================================================

export function AddRowMenu({ onAddRow, disabled = false, className }: AddRowMenuProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [customText, setCustomText] = useState("");
  // 移除selectedType，因为只支持分隔线
  const menuRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // 点击外部关闭菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setIsOpen(false);
        setCustomText("");
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
      // 自动聚焦到输入框
      setTimeout(() => {
        inputRef.current?.focus();
      }, 100);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isOpen]);

  const handleAddRow = () => {
    const text = customText.trim() || "分组标题";
    onAddRow('separator', text);
    setIsOpen(false);
    setCustomText("");
  };

  const getTypeIcon = () => {
    return (
      <svg className="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
        <path fillRule="evenodd" d="M3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clipRule="evenodd" />
      </svg>
    );
  };

  if (!isOpen) {
    return (
      <Button
        variant="outline"
        size="sm"
        onClick={() => setIsOpen(true)}
        disabled={disabled}
        className={cn("flex items-center gap-2", className)}
      >
        <svg className="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
          <path fillRule="evenodd" d="M3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clipRule="evenodd" />
        </svg>
        添加分隔线
      </Button>
    );
  }

  return (
    <div ref={menuRef} className={cn("relative", className)}>
      <div className="absolute top-0 left-0 z-50 bg-white border border-gray-200 rounded-lg shadow-lg p-4 w-80 animate-in fade-in-0 zoom-in-95 duration-200">
        {/* 标题 */}
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-sm font-medium text-gray-900">添加新行</h3>
          <button
            onClick={() => {
              setIsOpen(false);
              setCustomText("");
            }}
            className="text-gray-400 hover:text-gray-600 transition-colors p-1 hover:bg-gray-100 rounded"
          >
            <svg className="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
            </svg>
          </button>
        </div>

        {/* 行类型选择 - 只显示分隔线 */}
        <div className="space-y-2 mb-4">
          <label className="text-xs font-medium text-gray-700">添加分隔线</label>
          <div className="p-3 bg-gray-50 rounded-lg border">
            <div className="flex items-center gap-2 text-sm font-medium text-gray-900">
              {getTypeIcon()}
              <span>分隔线</span>
            </div>
            <p className="text-xs text-gray-500 mt-1">
              用于分组显示不同类型的指标，点击分隔线不会影响图表显示
            </p>
          </div>
        </div>

        {/* 自定义文本输入 */}
        <div className="space-y-2 mb-4">
          <label className="text-xs font-medium text-gray-700">
            分隔线文字
            <span className="text-gray-500 ml-1">(可选)</span>
          </label>
          <input
            ref={inputRef}
            type="text"
            value={customText}
            onChange={(e) => setCustomText(e.target.value)}
            placeholder="分组标题"
            className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                handleAddRow();
              } else if (e.key === 'Escape') {
                setIsOpen(false);
                setCustomText("");
              }
            }}
          />
        </div>

        {/* 操作按钮 */}
        <div className="flex items-center justify-end gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => {
              setIsOpen(false);
              setCustomText("");
            }}
          >
            取消
          </Button>
          <Button
            size="sm"
            onClick={handleAddRow}
          >
            添加分隔线
          </Button>
        </div>
      </div>
    </div>
  );
}