/**
 * 级联选项可视化编辑器
 * 提供树形界面来编辑级联数据
 */

import React, { useState } from 'react';
import { Button, Input, Space, Popconfirm, Typography, Tooltip } from 'antd';
import { PlusOutlined, DeleteOutlined, EditOutlined, PlusCircleOutlined } from '@ant-design/icons';
import type { CascadeFieldOption } from '../types';

const { Text } = Typography;

interface CascadeOptionEditorProps {
  value?: CascadeFieldOption[];
  onChange?: (value: CascadeFieldOption[]) => void;
}

interface OptionItemProps {
  option: CascadeFieldOption;
  level: number;
  onUpdate: (option: CascadeFieldOption) => void;
  onDelete: () => void;
  onAddChild: () => void;
}

/**
 * 单个选项编辑项
 */
const OptionItem: React.FC<OptionItemProps> = ({ option, level, onUpdate, onDelete, onAddChild }) => {
  const [editing, setEditing] = useState(false);
  const [label, setLabel] = useState(option.label);
  const [value, setValue] = useState(option.value);

  const handleSave = () => {
    onUpdate({ ...option, label, value: value || label });
    setEditing(false);
  };

  const handleCancel = () => {
    setLabel(option.label);
    setValue(option.value);
    setEditing(false);
  };

  const paddingLeft = level * 24;

  return (
    <div style={{ marginBottom: 8 }}>
      {/* 当前选项 */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          padding: '8px 12px',
          backgroundColor: level % 2 === 0 ? '#fafafa' : '#f5f5f5',
          borderRadius: 4,
          paddingLeft: paddingLeft + 12,
          border: '1px solid #e8e8e8',
        }}
      >
        {editing ? (
          <>
            <Input
              size="small"
              placeholder="标签"
              value={label}
              onChange={(e) => setLabel(e.target.value)}
              style={{ width: 120, marginRight: 8 }}
            />
            <Input
              size="small"
              placeholder="值（可选）"
              value={value}
              onChange={(e) => setValue(e.target.value)}
              style={{ width: 120, marginRight: 8 }}
            />
            <Button size="small" type="primary" onClick={handleSave} style={{ marginRight: 4 }}>
              保存
            </Button>
            <Button size="small" onClick={handleCancel}>
              取消
            </Button>
          </>
        ) : (
          <>
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8 }}>
              <Text strong>{option.label}</Text>
              <Text type="secondary" style={{ fontSize: 12 }}>
                ({option.value})
              </Text>
              {option.children && option.children.length > 0 && (
                <Text type="secondary" style={{ fontSize: 12 }}>
                  [{option.children.length} 个子项]
                </Text>
              )}
            </div>
            <Space size="small">
              <Tooltip title="添加子选项">
                <Button
                  size="small"
                  type="text"
                  icon={<PlusCircleOutlined />}
                  onClick={onAddChild}
                />
              </Tooltip>
              <Tooltip title="编辑">
                <Button
                  size="small"
                  type="text"
                  icon={<EditOutlined />}
                  onClick={() => setEditing(true)}
                />
              </Tooltip>
              <Popconfirm
                title="确定删除此选项吗？"
                description={option.children?.length ? '将同时删除所有子选项' : undefined}
                onConfirm={onDelete}
                okText="确定"
                cancelText="取消"
              >
                <Tooltip title="删除">
                  <Button size="small" type="text" danger icon={<DeleteOutlined />} />
                </Tooltip>
              </Popconfirm>
            </Space>
          </>
        )}
      </div>

      {/* 子选项 */}
      {option.children && option.children.length > 0 && (
        <div style={{ marginTop: 4 }}>
          {option.children.map((child, index) => (
            <OptionItem
              key={index}
              option={child}
              level={level + 1}
              onUpdate={(updatedChild) => {
                const newChildren = [...(option.children || [])];
                newChildren[index] = updatedChild;
                onUpdate({ ...option, children: newChildren });
              }}
              onDelete={() => {
                const newChildren = option.children?.filter((_, i) => i !== index) || [];
                onUpdate({ ...option, children: newChildren.length > 0 ? newChildren : undefined });
              }}
              onAddChild={() => {
                const newChild: CascadeFieldOption = {
                  label: '新选项',
                  value: `option_${Date.now()}`,
                };
                const newChildren = [...(child.children || []), newChild];
                const updatedChild = { ...child, children: newChildren };
                const newChildren2 = [...(option.children || [])];
                newChildren2[index] = updatedChild;
                onUpdate({ ...option, children: newChildren2 });
              }}
            />
          ))}
        </div>
      )}
    </div>
  );
};

/**
 * 级联选项编辑器主组件
 */
const CascadeOptionEditor: React.FC<CascadeOptionEditorProps> = ({ value = [], onChange }) => {
  const handleAddOption = () => {
    const newOption: CascadeFieldOption = {
      label: '新选项',
      value: `option_${Date.now()}`,
    };
    onChange?.([...value, newOption]);
  };

  const handleUpdateOption = (index: number, updatedOption: CascadeFieldOption) => {
    const newOptions = [...value];
    newOptions[index] = updatedOption;
    onChange?.(newOptions);
  };

  const handleDeleteOption = (index: number) => {
    const newOptions = value.filter((_, i) => i !== index);
    onChange?.(newOptions);
  };

  const handleAddChild = (index: number) => {
    const newChild: CascadeFieldOption = {
      label: '新子选项',
      value: `child_${Date.now()}`,
    };
    const newOptions = [...value];
    const currentOption = newOptions[index];
    newOptions[index] = {
      ...currentOption,
      children: [...(currentOption.children || []), newChild],
    };
    onChange?.(newOptions);
  };

  return (
    <div>
      <div style={{ marginBottom: 12 }}>
        <Button type="dashed" icon={<PlusOutlined />} onClick={handleAddOption} block>
          添加顶级选项
        </Button>
      </div>

      {value.length === 0 ? (
        <div
          style={{
            padding: 24,
            textAlign: 'center',
            color: '#8c8c8c',
            backgroundColor: '#fafafa',
            borderRadius: 4,
            border: '1px dashed #d9d9d9',
          }}
        >
          暂无选项，点击上方按钮添加
        </div>
      ) : (
        <div>
          {value.map((option, index) => (
            <OptionItem
              key={index}
              option={option}
              level={0}
              onUpdate={(updatedOption) => handleUpdateOption(index, updatedOption)}
              onDelete={() => handleDeleteOption(index)}
              onAddChild={() => handleAddChild(index)}
            />
          ))}
        </div>
      )}

      <div
        style={{
          marginTop: 12,
          padding: 12,
          background: '#f5f5f5',
          borderRadius: 4,
          fontSize: 12,
          color: '#666',
        }}
      >
        <div>
          <strong>💡 使用提示：</strong>
        </div>
        <div style={{ marginTop: 4 }}>1. 点击"添加顶级选项"创建第一级选项</div>
        <div>2. 点击 <PlusCircleOutlined /> 图标为选项添加子级</div>
        <div>3. 支持多级嵌套，构建完整的级联结构</div>
        <div>4. 值（value）留空时将自动使用标签（label）作为值</div>
      </div>
    </div>
  );
};

export default CascadeOptionEditor;

