/**
 * 联动规则编辑器
 */

import React from 'react';
import { Select, Input, Button, Space, Typography } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import type { LinkageRule, LinkageCondition, FieldConfig } from '../types';

const { Text } = Typography;

interface LinkageRuleEditorProps {
  value?: LinkageRule[];
  onChange?: (value: LinkageRule[]) => void;
  allFields?: FieldConfig[];  // 所有字段，用于联动字段选择
}

const LinkageRuleEditor: React.FC<LinkageRuleEditorProps> = ({ 
  value = [], 
  onChange,
  allFields = [] 
}) => {
  const handleAddRule = () => {
    const newRule: LinkageRule = {
      id: `rule_${Date.now()}`,
      type: 'visible',
      conditions: [],
      action: false,
    };
    onChange?.([...value, newRule]);
  };

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

  const handleRuleChange = (index: number, field: keyof LinkageRule, fieldValue: any) => {
    const newRules = [...value];
    newRules[index] = { ...newRules[index], [field]: fieldValue };
    onChange?.(newRules);
  };

  const handleAddCondition = (ruleIndex: number) => {
    const newCondition: LinkageCondition = {
      field: '',
      operator: '==',
      value: '',
    };
    const newRules = [...value];
    newRules[ruleIndex] = {
      ...newRules[ruleIndex],
      conditions: [...newRules[ruleIndex].conditions, newCondition],
    };
    onChange?.(newRules);
  };

  const handleDeleteCondition = (ruleIndex: number, conditionIndex: number) => {
    const newRules = [...value];
    newRules[ruleIndex] = {
      ...newRules[ruleIndex],
      conditions: newRules[ruleIndex].conditions.filter((_, i) => i !== conditionIndex),
    };
    onChange?.(newRules);
  };

  const handleConditionChange = (
    ruleIndex: number,
    conditionIndex: number,
    field: keyof LinkageCondition,
    fieldValue: any
  ) => {
    const newRules = [...value];
    const newConditions = [...newRules[ruleIndex].conditions];
    newConditions[conditionIndex] = { ...newConditions[conditionIndex], [field]: fieldValue };
    newRules[ruleIndex] = { ...newRules[ruleIndex], conditions: newConditions };
    onChange?.(newRules);
  };

  const renderActionInput = (rule: LinkageRule, index: number) => {
    switch (rule.type) {
      case 'visible':
      case 'disabled':
      case 'required':
        return (
          <div>
            <Text style={{ fontSize: 12, marginBottom: 4, display: 'block' }}>
              {rule.type === 'visible' ? '显示/隐藏' : rule.type === 'disabled' ? '禁用/启用' : '必填/非必填'}
            </Text>
            <Select
              style={{ width: '100%' }}
              value={rule.action}
              onChange={(val) => handleRuleChange(index, 'action', val)}
            >
              <Select.Option value={true}>
                {rule.type === 'visible' ? '显示' : rule.type === 'disabled' ? '禁用' : '必填'}
              </Select.Option>
              <Select.Option value={false}>
                {rule.type === 'visible' ? '隐藏' : rule.type === 'disabled' ? '启用' : '非必填'}
              </Select.Option>
            </Select>
          </div>
        );
      case 'value':
        return (
          <div>
            <Text style={{ fontSize: 12, marginBottom: 4, display: 'block' }}>赋值</Text>
            <Input
              placeholder="输入要设置的值"
              value={rule.action}
              onChange={(e) => handleRuleChange(index, 'action', e.target.value)}
            />
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <Text strong>联动规则</Text>
        <Button type="dashed" size="small" icon={<PlusOutlined />} onClick={handleAddRule}>
          添加规则
        </Button>
      </div>

      {value.length === 0 ? (
        <div style={{ padding: '24px 0', textAlign: 'center', color: '#8c8c8c', fontSize: 12 }}>
          暂无联动规则，点击上方按钮添加
        </div>
      ) : (
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          {value.map((rule, ruleIndex) => (
            <div
              key={rule.id}
              style={{
                padding: 12,
                border: '1px solid #e8e8e8',
                borderRadius: 4,
                background: '#fafafa',
              }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                <Text style={{ fontSize: 12, color: '#666' }}>规则 {ruleIndex + 1}</Text>
                <Button
                  type="text"
                  size="small"
                  danger
                  icon={<DeleteOutlined />}
                  onClick={() => handleDeleteRule(ruleIndex)}
                />
              </div>

              <Space direction="vertical" style={{ width: '100%' }} size="small">
                <div>
                  <Text style={{ fontSize: 12, marginBottom: 4, display: 'block' }}>联动类型</Text>
                  <Select
                    style={{ width: '100%' }}
                    value={rule.type}
                    onChange={(val) => handleRuleChange(ruleIndex, 'type', val)}
                  >
                    <Select.Option value="visible">显示/隐藏</Select.Option>
                    <Select.Option value="disabled">禁用/启用</Select.Option>
                    <Select.Option value="required">必填/非必填</Select.Option>
                    <Select.Option value="value">值联动</Select.Option>
                  </Select>
                </div>

                <div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
                    <Text style={{ fontSize: 12 }}>触发条件（满足所有条件时生效）</Text>
                    <Button
                      type="link"
                      size="small"
                      icon={<PlusOutlined />}
                      onClick={() => handleAddCondition(ruleIndex)}
                    >
                      添加条件
                    </Button>
                  </div>

                  {rule.conditions.length === 0 ? (
                    <div style={{ padding: 8, textAlign: 'center', color: '#999', fontSize: 11, border: '1px dashed #d9d9d9', borderRadius: 4 }}>
                      暂无条件
                    </div>
                  ) : (
                    <Space direction="vertical" style={{ width: '100%' }} size="small">
                      {rule.conditions.map((condition, conditionIndex) => (
                        <div
                          key={conditionIndex}
                          style={{
                            padding: 8,
                            background: '#fff',
                            border: '1px solid #e8e8e8',
                            borderRadius: 4,
                          }}
                        >
                          <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
                            <Select
                              style={{ flex: 1 }}
                              placeholder={allFields.length === 0 ? "暂无可选字段" : "选择字段"}
                              value={condition.field}
                              onChange={(val) =>
                                handleConditionChange(ruleIndex, conditionIndex, 'field', val)
                              }
                              notFoundContent={allFields.length === 0 ? "请先添加其他字段" : "暂无匹配字段"}
                            >
                              {allFields.map((field) => (
                                <Select.Option key={field.name} value={field.name}>
                                  {field.label} ({field.name})
                                </Select.Option>
                              ))}
                            </Select>

                            <Select
                              style={{ width: 80 }}
                              value={condition.operator}
                              onChange={(val) =>
                                handleConditionChange(ruleIndex, conditionIndex, 'operator', val)
                              }
                            >
                              <Select.Option value="==">等于</Select.Option>
                              <Select.Option value="!=">不等于</Select.Option>
                              <Select.Option value=">">大于</Select.Option>
                              <Select.Option value="<">小于</Select.Option>
                              <Select.Option value=">=">大于等于</Select.Option>
                              <Select.Option value="<=">小于等于</Select.Option>
                              <Select.Option value="includes">包含</Select.Option>
                              <Select.Option value="notIncludes">不包含</Select.Option>
                            </Select>

                            <Input
                              style={{ flex: 1 }}
                              placeholder="值"
                              value={condition.value}
                              onChange={(e) =>
                                handleConditionChange(ruleIndex, conditionIndex, 'value', e.target.value)
                              }
                            />

                            <Button
                              type="text"
                              size="small"
                              danger
                              icon={<DeleteOutlined />}
                              onClick={() => handleDeleteCondition(ruleIndex, conditionIndex)}
                            />
                          </div>
                        </div>
                      ))}
                    </Space>
                  )}
                </div>

                {renderActionInput(rule, ruleIndex)}
              </Space>
            </div>
          ))}
        </Space>
      )}
    </div>
  );
};

export default LinkageRuleEditor;

