import React, { useState } from 'react';
import { Button, Input, Popconfirm, Select, Typography } from 'antd';
import { DeleteOutlined, SaveOutlined } from '@ant-design/icons';
import api from '../api';
import { message } from '../ui/app-message';
import { useApiMutation } from '../hooks/useApiMutation';
import { STUDENT_FIELDS } from './JinshujuMatchModal.types';
import type { JinshujuFormField, MatchRule } from './JinshujuMatchModal.types';

const { Text } = Typography;

interface RuleEditorProps {
  rule: MatchRule | null;
  formToken: string;
  fields: JinshujuFormField[];
  onSave: () => void;
  onDelete: (id: number) => void;
  onCancel: () => void;
}

const RuleEditor: React.FC<RuleEditorProps> = ({
  rule,
  formToken,
  fields,
  onSave,
  onDelete,
  onCancel,
}) => {
  const [name, setName] = useState(rule?.name ?? '');
  const [mappings, setMappings] = useState<Record<string, string>>(
    rule?.mappings ?? { name: 'field_1', phone: 'field_2' },
  );
  const [saving, setSaving] = useState(false);

  const saveMutation = useApiMutation(
    async (payload: { name: string; mappings: Record<string, string> }) =>
      rule
        ? api.put(`/sync/jinshuju/rules/${rule.id}`, payload)
        : api.post('/sync/jinshuju/rules', { ...payload, formToken }),
    {
      invalidate: [['sync', 'jinshuju', 'rules']],
      onSuccess: () => {
        message.success('规则已保存');
        onSave();
      },
    },
  );

  const handleSave = async () => {
    if (!name.trim()) {
      message.warning('请输入规则名称');
      return;
    }
    setSaving(true);
    try {
      await saveMutation.mutateAsync({ name, mappings });
    } catch {
      // 错误提示由 useApiMutation 统一处理
    } finally {
      setSaving(false);
    }
  };

  return (
    <div style={{ padding: '12px 0' }}>
      <Input
        placeholder="规则名称"
        value={name}
        onChange={(e) => setName(e.target.value)}
        style={{ marginBottom: 12 }}
      />
      <Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
        选择金数据字段映射到学生资料
      </Text>
      {STUDENT_FIELDS.map((sf) => (
        <div
          key={sf.key}
          style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}
        >
          <Text style={{ width: 100, textAlign: 'right', fontSize: 13 }}>{sf.label}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>
            ←
          </Text>
          <Select
            allowClear
            showSearch
            optionFilterProp="label"
            placeholder="选择金数据字段"
            value={mappings[sf.key]}
            style={{ flex: 1 }}
            options={fields.map((field) => ({
              value: field.key,
              label: `${field.label}（${field.key}）`,
            }))}
            onChange={(value) =>
              setMappings((prev) => {
                const next = { ...prev };
                if (value) next[sf.key] = value;
                else delete next[sf.key];
                return next;
              })
            }
          />
        </div>
      ))}
      <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
        <Button type="primary" icon={<SaveOutlined />} loading={saving} onClick={handleSave}>
          保存
        </Button>
        {rule && (
          <Popconfirm title="确定删除此规则？" onConfirm={() => onDelete(rule.id)}>
            <Button danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        )}
        <Button onClick={onCancel}>取消</Button>
      </div>
    </div>
  );
};

export default RuleEditor;
