import React, { useState } from 'react';
import {
  type InspectorAction,
  SKILL_MENU_CONFIG,
} from '../components/agentPanel/inspectorActions';

interface Props {
  open: boolean;
  popupRight: number;
  isDataMngtList: boolean;
  pageType: string;
  onClose: () => void;
  onAddData: () => void;
  onAddPage: () => void;
  onEditData: () => void;
  onDeleteData: () => void;
  onFormSkill: (skill: string, label: string) => void;
}

export default function SkillMenu(props: Props) {
  const { open, popupRight, isDataMngtList, pageType, onClose } = props;
  const isFormPage = pageType === 'create' || pageType === 'edit';

  const [pendingSkill, setPendingSkill] = useState<InspectorAction | null>(
    null,
  );
  const [inputValue, setInputValue] = useState('');

  const actionCallbacks: Record<string, () => void> = {
    editData: () => {
      props.onClose();
      props.onEditData();
    },
    deleteData: () => {
      props.onClose();
      props.onDeleteData();
    },
    addData: () => {
      props.onClose();
      props.onAddData();
    },
    addPage: () => {
      props.onClose();
      props.onAddPage();
    },
  };

  function handleItemClick(item: InspectorAction, disabled?: boolean) {
    if (disabled) return;
    if (item.actionKey) {
      actionCallbacks[item.actionKey]?.();
    } else if (item.requiresInput || item.requiresConfirm) {
      setPendingSkill(item);
      setInputValue('');
    } else {
      props.onFormSkill(item.skill!, item.label);
    }
  }

  function handleModalConfirm() {
    if (!pendingSkill) return;
    const details = inputValue.trim();
    const prompt = details
      ? `${pendingSkill.label}。具体要求：\n${details}`
      : pendingSkill.label;
    props.onFormSkill(pendingSkill.skill!, prompt);
    setPendingSkill(null);
  }

  function handleModalCancel() {
    setPendingSkill(null);
  }

  return (
    <>
      {open && (
        <div id="skill-menu-backdrop" className="open" onClick={onClose} />
      )}
      <div
        id="skill-menu-popup"
        className={open ? 'open' : ''}
        style={{ right: popupRight }}
      >
        {/* 本页面 */}
        <div className="skill-menu-section">
          <div className="skill-menu-group-label">本页面/模块</div>
          {SKILL_MENU_CONFIG.page.map((item) => {
            const disabled = !isDataMngtList;
            return (
              <button
                key={item.label}
                className="skill-menu-item"
                disabled={disabled}
                onClick={() => handleItemClick(item, disabled)}
              >
                {item.label}
              </button>
            );
          })}
          {isFormPage &&
            SKILL_MENU_CONFIG.formPage.map((item) => (
              <button
                key={item.skill}
                className="skill-menu-item"
                onClick={() => handleItemClick(item)}
              >
                {item.label}
              </button>
            ))}
        </div>

        {/* 本项目 */}
        <div className="skill-menu-section">
          <div className="skill-menu-group-label">本项目</div>
          {SKILL_MENU_CONFIG.project.map((item) => (
            <button
              key={item.label}
              className="skill-menu-item"
              onClick={() => handleItemClick(item)}
            >
              {item.label}
            </button>
          ))}
        </div>
      </div>

      {/* 二次确认 Modal（requiresConfirm） */}
      {pendingSkill?.requiresConfirm && (
        <div
          id="delete-data-confirm-overlay"
          onClick={(e) => {
            if (e.target === e.currentTarget) handleModalCancel();
          }}
        >
          <div id="delete-data-confirm-card">
            <h3>{pendingSkill.label}</h3>
            {pendingSkill.confirmDescription && (
              <p>{pendingSkill.confirmDescription}</p>
            )}
            <div className="delete-confirm-actions">
              <button className="undo-btn-cancel" onClick={handleModalCancel}>
                取消
              </button>
              <button
                className="delete-data-btn-confirm"
                onClick={handleModalConfirm}
              >
                确认
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 补充输入 Modal（requiresInput） */}
      {pendingSkill?.requiresInput && (
        <div
          id="edit-data-modal-overlay"
          onClick={(e) => {
            if (e.target === e.currentTarget) handleModalCancel();
          }}
        >
          <div id="edit-data-modal-card">
            <div className="add-data-modal-header">
              <h3>{pendingSkill.label}</h3>
              <button
                className="add-data-modal-close"
                onClick={handleModalCancel}
              >
                ×
              </button>
            </div>
            <div className="add-data-modal-body">
              <textarea
                className="add-data-free-textarea"
                placeholder={pendingSkill.inputPlaceholder}
                rows={5}
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                autoFocus
              />
            </div>
            <div className="add-data-modal-footer">
              <button
                className="add-data-btn-cancel"
                onClick={handleModalCancel}
              >
                取消
              </button>
              <button
                className="add-data-btn-confirm"
                onClick={handleModalConfirm}
              >
                确认
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
