/**
 * 冲突 diff 交互表格 — 展示新旧值对比，支持逐行选择替换/保留。
 *
 * - 每行显示：字段名、旧值、新值、操作选项（替换/保留 Radio）
 * - 支持"全部替换"和"全部保留"快捷操作按钮
 * - 确认按钮提交 resolutions 数组
 * - Props: conflicts（冲突数据）、onConfirm（确认回调）、loading
 */

import React, { useState, useCallback } from "react";
import { Table, Radio, Button, Space } from "antd";
import type { ColumnsType } from "antd/es/table";

/* ------------------------------------------------------------------ */
/*  类型定义                                                           */
/* ------------------------------------------------------------------ */

/** 单个字段的 diff */
export interface FieldDiff {
  field: string;
  oldValue: string | number | null;
  newValue: string | number | null;
}

/** 一行冲突数据 */
export interface ConflictRow {
  rowIndex: number;
  diffs: FieldDiff[];
}

/** 解决方案 */
export interface Resolution {
  rowIndex: number;
  action: "replace" | "keep";
}

/* ------------------------------------------------------------------ */
/*  Props                                                              */
/* ------------------------------------------------------------------ */

interface DiffTableProps {
  conflicts: ConflictRow[];
  onConfirm: (resolutions: Resolution[]) => void;
  loading?: boolean;
}

/* ------------------------------------------------------------------ */
/*  展开行内的字段 diff 表格                                            */
/* ------------------------------------------------------------------ */

const FieldDiffTable: React.FC<{ diffs: FieldDiff[] }> = ({ diffs }) => {
  const columns: ColumnsType<FieldDiff> = [
    { title: "字段名", dataIndex: "field", key: "field", width: 160 },
    {
      title: "旧值",
      dataIndex: "oldValue",
      key: "oldValue",
      render: (v) => (v !== null && v !== undefined ? String(v) : "-"),
    },
    {
      title: "新值",
      dataIndex: "newValue",
      key: "newValue",
      render: (v) => (v !== null && v !== undefined ? String(v) : "-"),
    },
  ];

  return (
    <Table<FieldDiff>
      rowKey="field"
      columns={columns}
      dataSource={diffs}
      pagination={false}
      size="small"
      style={{ marginBottom: 0 }}
    />
  );
};

/* ------------------------------------------------------------------ */
/*  主组件                                                             */
/* ------------------------------------------------------------------ */

const DiffTable: React.FC<DiffTableProps> = ({ conflicts, onConfirm, loading }) => {
  // 每行的选择状态：rowIndex → action
  const [selections, setSelections] = useState<Record<number, "replace" | "keep">>({});

  const setAction = useCallback((rowIndex: number, action: "replace" | "keep") => {
    setSelections((prev) => ({ ...prev, [rowIndex]: action }));
  }, []);

  /** 全部替换 */
  const handleReplaceAll = useCallback(() => {
    const all: Record<number, "replace" | "keep"> = {};
    conflicts.forEach((c) => {
      all[c.rowIndex] = "replace";
    });
    setSelections(all);
  }, [conflicts]);

  /** 全部保留 */
  const handleKeepAll = useCallback(() => {
    const all: Record<number, "replace" | "keep"> = {};
    conflicts.forEach((c) => {
      all[c.rowIndex] = "keep";
    });
    setSelections(all);
  }, [conflicts]);

  /** 是否所有行都已选择 */
  const allSelected = conflicts.every((c) => selections[c.rowIndex] !== undefined);

  /** 提交 */
  const handleConfirm = () => {
    const resolutions: Resolution[] = conflicts.map((c) => ({
      rowIndex: c.rowIndex,
      action: selections[c.rowIndex] ?? "keep",
    }));
    onConfirm(resolutions);
  };

  const columns: ColumnsType<ConflictRow> = [
    {
      title: "行号",
      dataIndex: "rowIndex",
      key: "rowIndex",
      width: 80,
    },
    {
      title: "冲突字段数",
      key: "diffCount",
      width: 100,
      render: (_, record) => record.diffs.length,
    },
    {
      title: "操作",
      key: "action",
      width: 200,
      render: (_, record) => (
        <Radio.Group
          value={selections[record.rowIndex]}
          onChange={(e) => setAction(record.rowIndex, e.target.value)}
        >
          <Radio value="replace">替换</Radio>
          <Radio value="keep">保留</Radio>
        </Radio.Group>
      ),
    },
  ];

  return (
    <Space direction="vertical" size="middle" style={{ width: "100%" }}>
      {/* 快捷操作 */}
      <Space>
        <Button onClick={handleReplaceAll}>全部替换</Button>
        <Button onClick={handleKeepAll}>全部保留</Button>
      </Space>

      {/* 冲突表格 */}
      <Table<ConflictRow>
        rowKey="rowIndex"
        columns={columns}
        dataSource={conflicts}
        pagination={false}
        size="small"
        expandable={{
          expandedRowRender: (record) => <FieldDiffTable diffs={record.diffs} />,
          defaultExpandAllRows: true,
        }}
      />

      {/* 确认按钮 */}
      <Button
        type="primary"
        size="large"
        onClick={handleConfirm}
        loading={loading}
        disabled={!allSelected}
      >
        确认提交（{conflicts.length} 行冲突）
      </Button>
      {!allSelected && (
        <span style={{ color: "#999", fontSize: 12 }}>
          请为所有冲突行选择操作后再提交
        </span>
      )}
    </Space>
  );
};

export default DiffTable;
