import React, { useEffect, useRef, useState } from 'react';
import { Button, Form, Input, Modal, Popconfirm, Select, Spin, Steps, Tag, Typography } from 'antd';
import {
  CloudUploadOutlined,
  DeleteOutlined,
  EditOutlined,
  LinkOutlined,
  PlusOutlined,
  SaveOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import api from '../api';
import { message } from '../ui/app-message';

const { Text } = Typography;

// ── Types ──

interface JinshujuEntryRow {
  serialNumber: number;
  name: string;
  phone: string | null;
  suggestedStudent: {
    id: number;
    name: string;
    phone: string | null;
    studentNo: string | null;
  } | null;
}

interface StudentOption {
  id: number;
  name: string;
  phone: string | null;
  studentNo: string | null;
}

interface PreviewResponse {
  success: boolean;
  entries: JinshujuEntryRow[];
  students: StudentOption[];
}

interface MatchRule {
  id: number;
  name: string;
  formToken: string;
  mappings: Record<string, string>;
  createdAt: string;
}

interface JinshujuFormField {
  key: string;
  label: string;
  type: string;
}

type MatchDecision =
  | { action: 'match'; matchStudentId: number }
  | { action: 'create'; createName: string; createPhone: string }
  | { action: 'skip' };

// ── Constants ──

const ROW_HEIGHT = 72;
const LEFT_WIDTH = 260;
const GAP = 80;

const STUDENT_FIELDS = [
  { key: 'name', label: '姓名' },
  { key: 'phone', label: '手机号' },
  { key: 'idNumber', label: '身份证号' },
  { key: 'gender', label: '性别' },
  { key: 'ethnicity', label: '民族' },
  { key: 'emergencyContact', label: '紧急联系人' },
  { key: 'emergencyPhone', label: '紧急联系电话' },
  { key: 'studentNo', label: '学号' },
];

// ── MatchSelector sub-component ──

interface MatchSelectorProps {
  entry: JinshujuEntryRow;
  decision: MatchDecision | undefined;
  studentOptions: StudentOption[];
  onChange: (d: MatchDecision) => void;
}

const MatchSelector: React.FC<MatchSelectorProps> = ({ entry, decision, studentOptions, onChange }) => {
  const action = decision?.action ?? 'skip';

  if (action === 'match') {
    const matchD = decision as { action: 'match'; matchStudentId: number };
    const matchedStudent = studentOptions.find((s) => s.id === matchD.matchStudentId);
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
        <Tag color="blue" icon={<LinkOutlined />}>已匹配</Tag>
        <Text style={{ flex: 1 }}>
          {matchedStudent?.name ?? '未知'}
          {matchedStudent?.studentNo && (
            <Text type="secondary" style={{ fontSize: 12, marginLeft: 4 }}>
              ({matchedStudent.studentNo})
            </Text>
          )}
        </Text>
        <Button size="small" type="link" danger onClick={() => onChange({ action: 'skip' })}>取消</Button>
      </div>
    );
  }

  if (action === 'create') {
    const createD = decision as { action: 'create'; createName: string; createPhone: string };
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
        <Tag color="green" icon={<PlusOutlined />}>将新建</Tag>
        <Input size="small" value={createD.createName} placeholder="姓名" style={{ width: 100 }}
          onChange={(e) => onChange({ action: 'create', createName: e.target.value, createPhone: createD.createPhone })} />
        <Input size="small" value={createD.createPhone} placeholder="手机号" style={{ width: 120 }}
          onChange={(e) => onChange({ action: 'create', createName: createD.createName, createPhone: e.target.value })} />
        <Button size="small" type="link" danger onClick={() => onChange({ action: 'skip' })}>取消</Button>
      </div>
    );
  }

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
      <Select showSearch size="small" placeholder="搜索学生…" style={{ flex: 1 }} value={undefined}
        filterOption={(input, option) => ((option?.label as string) || '').toLowerCase().includes(input.toLowerCase())}
        options={studentOptions.map((s) => ({
          value: s.id,
          label: `${s.name}${s.phone ? ` (${s.phone})` : ''}${s.studentNo ? ` [${s.studentNo}]` : ''}`,
        }))}
        onChange={(studentId: number) => onChange({ action: 'match', matchStudentId: studentId })} />
      <Button size="small" type="dashed" icon={<PlusOutlined />}
        onClick={() => onChange({ action: 'create', createName: entry.name || '', createPhone: entry.phone || '' })}>
        新建
      </Button>
      <Button size="small" type="link" onClick={() => onChange({ action: 'skip' })}>跳过</Button>
    </div>
  );
};

// ── Rule Editor sub-component ──

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 handleSave = async () => {
    if (!name.trim()) { message.warning('请输入规则名称'); return; }
    setSaving(true);
    try {
      if (rule) {
        await api.put(`/sync/jinshuju/rules/${rule.id}`, { name, mappings });
      } else {
        await api.post('/sync/jinshuju/rules', { name, formToken, mappings });
      }
      message.success('规则已保存');
      onSave();
    } catch (e: unknown) {
      const err = e as { message?: string };
      if (err?.message) message.error(err.message);
    } 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>
  );
};

// ── Main MatchModal ──

interface MatchModalProps {
  open: boolean;
  onClose: () => void;
  onApplied: () => void;
}

const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplied }) => {
  const [step, setStep] = useState<'connection' | 'rule' | 'match' | 'applying'>('connection');
  const [loading, setLoading] = useState(false);
  const [selectedRuleId, setSelectedRuleId] = useState<number | undefined>();
  const [rules, setRules] = useState<MatchRule[]>([]);
  const [editingRule, setEditingRule] = useState<MatchRule | null>(null);
  const [showRuleEditor, setShowRuleEditor] = useState(false);
  const [credForm] = Form.useForm();
  const formToken = Form.useWatch('formToken', credForm) ?? '';

  const [entries, setEntries] = useState<JinshujuEntryRow[]>([]);
  const [studentOptions, setStudentOptions] = useState<StudentOption[]>([]);
  const [decisions, setDecisions] = useState<Map<number, MatchDecision>>(new Map());
  const leftRef = useRef<HTMLDivElement>(null);
  const rightRef = useRef<HTMLDivElement>(null);
  const [formFields, setFormFields] = useState<JinshujuFormField[]>([]);
  const [formName, setFormName] = useState('');
  const [scrollTop, setScrollTop] = useState(0);

  // Load rules on open
  useEffect(() => {
    if (open) loadRules();
  }, [open]);

  const loadRules = async () => {
    try {
      const res = await api.get<{ success: boolean; data: MatchRule[] }>('/sync/jinshuju/rules');
      if (res.success) setRules(res.data);
    } catch { /* ignore */ }
  };

  const handleConnectionNext = async () => {
    try {
      const values = await credForm.validateFields();
      setLoading(true);
      const response = await api.post<{
        success: boolean;
        data: { name: string; fields: JinshujuFormField[] };
      }>('/sync/jinshuju/fields', values);
      setFormFields(response.data.fields);
      setFormName(response.data.name);
      setStep('rule');
    } catch (error: unknown) {
      const apiError = error as { message?: string; errorFields?: unknown[] };
      if (!apiError.errorFields && apiError.message) message.error(apiError.message);
    } finally {
      setLoading(false);
    }
  };

  const handlePreview = async () => {
    try {
      const values = await credForm.validateFields();
      setLoading(true);
      const body: Record<string, unknown> = { ...values };
      if (selectedRuleId) body.ruleId = selectedRuleId;
      const res = await api.post<PreviewResponse>('/sync/jinshuju/preview', body);
      if (!res.success) throw new Error('预览失败');
      setEntries(res.entries);
      setStudentOptions(res.students);
      const initial = new Map<number, MatchDecision>();
      for (const entry of res.entries) {
        if (entry.suggestedStudent) {
          initial.set(entry.serialNumber, { action: 'match', matchStudentId: entry.suggestedStudent.id });
        }
      }
      setDecisions(initial);
      setStep('match');
    } catch (e: unknown) {
      const err = e as { message?: string };
      if (err?.message) message.error(err.message);
    } finally { setLoading(false); }
  };

  const handleApply = async () => {
    setLoading(true);
    setStep('applying');
    try {
      const decisionList = [...decisions.entries()].map(([serialNumber, d]) => ({ serialNumber, ...d }));
      const body: Record<string, unknown> = {
        ...credForm.getFieldsValue(),
        decisions: decisionList,
      };
      if (selectedRuleId) body.ruleId = selectedRuleId;
      const res = await api.post<{ success: boolean; log: { recordsCount: number; message?: string } }>(
        '/sync/jinshuju/apply', body,
      );
      if (res.success) {
        message.success(res.log.message || `处理 ${res.log.recordsCount} 条记录`);
        onApplied();
        reset();
      }
    } catch (e: unknown) {
      const err = e as { message?: string };
      if (err?.message) message.error(err.message);
      setStep('match');
    } finally { setLoading(false); }
  };

  const reset = () => {
    setStep('connection');
    setEntries([]);
    setStudentOptions([]);
    setDecisions(new Map());
    setSelectedRuleId(undefined);
    setFormFields([]);
    setFormName('');
    setShowRuleEditor(false);
    credForm.resetFields();
  };

  const handleClose = () => { reset(); onClose(); };
  const handleScroll = (source: 'left' | 'right') => {
    const el = source === 'left' ? leftRef.current : rightRef.current;
    if (el) setScrollTop(el.scrollTop);
  };

  useEffect(() => {
    if (leftRef.current) leftRef.current.scrollTop = scrollTop;
    if (rightRef.current) rightRef.current.scrollTop = scrollTop;
  }, [scrollTop]);

  const getDecision = (serial: number): MatchDecision | undefined => decisions.get(serial);
  const setDecision = (serial: number, d: MatchDecision) => setDecisions((prev) => new Map(prev).set(serial, d));
  const total = entries.length;
  const matched = [...decisions.values()].filter((d) => d.action !== 'skip').length;

  const visibleRules = rules.filter((rule) => rule.formToken === formToken);
  const selectedRule = visibleRules.find((rule) => rule.id === selectedRuleId) ?? null;

  // ── Render ──

  const renderConnectionStep = () => (
    <Form form={credForm} layout="vertical" style={{ marginTop: 24 }}>
      <Form.Item
        name="apiKey"
        label="API Key"
        extra="金数据个人中心 → API 中获取"
        rules={[{ required: true, message: '请输入 API Key' }]}
      >
        <Input placeholder="请输入 API Key" autoComplete="username" />
      </Form.Item>
      <Form.Item
        name="apiSecret"
        label="API Secret"
        rules={[{ required: true, message: '请输入 API Secret' }]}
      >
        <Input.Password placeholder="请输入 API Secret" autoComplete="current-password" />
      </Form.Item>
      <Form.Item
        name="formToken"
        label="表单 Token"
        extra="例如表单地址 /f/AbC123 中的 AbC123"
        rules={[{ required: true, message: '请输入表单 Token' }]}
      >
        <Input placeholder="请输入表单 Token" />
      </Form.Item>
    </Form>
  );

  const renderRuleStep = () => (
    <div style={{ marginTop: 24 }}>
      <div style={{ marginBottom: 12 }}>
        <Text strong>选择匹配规则</Text>
        <Text type="secondary" style={{ display: 'block', marginTop: 4 }}>
          已连接表单「{formName}」，共 {formFields.length} 个字段。选择已有规则或新建字段映射。
        </Text>
      </div>

      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
        <Select
          style={{ flex: 1 }}
          placeholder="默认规则：field_1 → 姓名，field_2 → 手机号"
          allowClear
          value={selectedRuleId}
          onChange={(value) => setSelectedRuleId(value)}
          options={visibleRules.map((rule) => ({ value: rule.id, label: rule.name }))}
        />
        {selectedRule ? (
          <Button
            icon={<EditOutlined />}
            onClick={() => {
              setEditingRule(selectedRule);
              setShowRuleEditor(true);
            }}
          >
            编辑
          </Button>
        ) : null}
        <Button
          icon={<PlusOutlined />}
          onClick={() => {
            setEditingRule(null);
            setShowRuleEditor(true);
          }}
        >
          新建规则
        </Button>
      </div>

      {visibleRules.length === 0 && !showRuleEditor ? (
        <Text type="secondary" style={{ display: 'block', marginTop: 12 }}>
          当前表单还没有保存的规则。
        </Text>
      ) : null}

      {showRuleEditor ? (
        <RuleEditor
          rule={editingRule}
          formToken={formToken}
          fields={formFields}
          onSave={() => {
            setShowRuleEditor(false);
            loadRules();
          }}
          onDelete={async (id) => {
            await api.delete(`/sync/jinshuju/rules/${id}`);
            message.success('规则已删除');
            if (selectedRuleId === id) setSelectedRuleId(undefined);
            setShowRuleEditor(false);
            loadRules();
          }}
          onCancel={() => setShowRuleEditor(false)}
        />
      ) : null}
    </div>
  );

  const renderMatchStep = () => {
    const svgHeight = entries.length * ROW_HEIGHT;
    const lines: React.ReactNode[] = [];
    entries.forEach((entry, i) => {
      const y = i * ROW_HEIGHT + ROW_HEIGHT / 2;
      const d = getDecision(entry.serialNumber);
      const isMatched = d?.action === 'match';
      const color = isMatched ? '#1677ff' : '#d9d9d9';
      lines.push(<line key={entry.serialNumber} x1={LEFT_WIDTH} y1={y} x2={LEFT_WIDTH + GAP} y2={y}
        stroke={color} strokeWidth={isMatched ? 2 : 1}
        strokeDasharray={isMatched ? undefined : '4 4'} opacity={isMatched ? 0.7 : 0.3} />);
    });

    return (
      <div style={{ position: 'relative' }}>
        <div style={{ marginBottom: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Text type="secondary">共 {total} 条，已匹配 {matched} 条</Text>
          <Button size="small" onClick={() => setDecisions(new Map())}>清除全部匹配</Button>
        </div>
        <div style={{ display: 'flex', position: 'relative' }}>
          <svg style={{ position: 'absolute', top: 0, left: 0, width: LEFT_WIDTH + GAP, height: svgHeight, pointerEvents: 'none', zIndex: 1 }}>
            {lines}
          </svg>
          <div ref={leftRef} onScroll={() => handleScroll('left')}
            style={{ width: LEFT_WIDTH, maxHeight: 480, overflowY: 'auto', flexShrink: 0 }}>
            {entries.map((entry, i) => {
              const d = getDecision(entry.serialNumber);
              const isMatched = d?.action === 'match';
              return (
                <div key={entry.serialNumber} style={{
                  height: ROW_HEIGHT, padding: '8px 12px', borderBottom: '1px solid #f0f0f0',
                  display: 'flex', flexDirection: 'column', justifyContent: 'center',
                  background: isMatched ? '#f6ffed' : i % 2 === 0 ? '#fafafa' : '#fff',
                  borderLeft: isMatched ? '3px solid #1677ff' : '3px solid transparent',
                }}>
                  <Text strong style={{ fontSize: 13 }}>{entry.name || <Text type="secondary">无姓名</Text>}</Text>
                  {entry.phone && <Text type="secondary" style={{ fontSize: 12 }}>{entry.phone}</Text>}
                  <Text type="secondary" style={{ fontSize: 11 }}>#{entry.serialNumber}</Text>
                </div>
              );
            })}
          </div>
          <div style={{ width: GAP, flexShrink: 0 }} />
          <div ref={rightRef} onScroll={() => handleScroll('right')}
            style={{ flex: 1, maxHeight: 480, overflowY: 'auto' }}>
            {entries.map((entry) => (
              <div key={entry.serialNumber} style={{
                height: ROW_HEIGHT, padding: '8px 12px', borderBottom: '1px solid #f0f0f0',
                display: 'flex', alignItems: 'center', gap: 8,
              }}>
                <MatchSelector entry={entry} decision={getDecision(entry.serialNumber)}
                  studentOptions={studentOptions}
                  onChange={(newD) => setDecision(entry.serialNumber, newD)} />
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  };

  const currentStep = step === 'connection' ? 0 : step === 'rule' ? 1 : 2;

  return (
    <Modal
      title="同步金数据"
      open={open}
      onCancel={handleClose}
      width={step === 'match' || step === 'applying' ? 900 : 640}
      maskClosable={false}
      footer={
        step === 'connection'
          ? [
              <Button key="cancel" onClick={handleClose}>取消</Button>,
              <Button key="next" type="primary" onClick={handleConnectionNext}>下一步</Button>,
            ]
          : step === 'rule'
            ? [
                <Button key="back" onClick={() => setStep('connection')}>上一步</Button>,
                <Button key="cancel" onClick={handleClose}>取消</Button>,
                <Button key="next" type="primary" icon={<SearchOutlined />} loading={loading} onClick={handlePreview}>
                  获取数据并下一步
                </Button>,
              ]
            : step === 'match'
              ? [
                  <Button key="back" onClick={() => setStep('rule')}>上一步</Button>,
                  <Button key="cancel" onClick={handleClose}>取消</Button>,
                  <Button key="apply" type="primary" icon={<CloudUploadOutlined />} loading={loading} onClick={handleApply}>
                    应用匹配
                  </Button>,
                ]
              : null
      }
    >
      <Steps
        current={currentStep}
        items={[
          { title: '连接表单' },
          { title: '匹配规则' },
          { title: '确认匹配' },
        ]}
      />
      {step === 'connection' ? renderConnectionStep() : null}
      {step === 'rule' ? renderRuleStep() : null}
      {step === 'match' ? renderMatchStep() : null}
      {step === 'applying' ? <Spin tip="正在同步..." style={{ display: 'block', margin: '48px auto' }} /> : null}
    </Modal>
  );
};

export default JinshujuMatchModal;
