/**
 * P18 客户转移日志页面。
 *
 * 展示 biz.coach_task_transfer_log 分页列表，支持门店/时间/助教筛选。
 */

import React, { useEffect, useState, useCallback } from "react";
import {
  Table, Card, Typography, Button, Space, DatePicker, InputNumber,
  Tag, Tooltip, message,
} from "antd";
import {
  ReloadOutlined, SwapOutlined, CheckCircleOutlined, CloseCircleOutlined,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";
import {
  fetchTransferLogs, type TransferLogItem, type TransferLogQuery,
} from "../api/taskEngine";

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;

function formatTime(raw: string | null): string {
  if (!raw) return "—";
  return dayjs(raw).format("YYYY-MM-DD HH:mm");
}

/** guard_checks JSON → 三项检查标签 */
function renderGuardChecks(checks: Record<string, unknown> | null) {
  if (!checks) return <Text type="secondary">—</Text>;
  return (
    <Space size={4} wrap>
      {Object.entries(checks).map(([k, v]) => (
        <Tag
          key={k}
          color={v ? "success" : "error"}
          icon={v ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
        >
          {k}
        </Tag>
      ))}
    </Space>
  );
}

const REASON_LABELS: Record<string, string> = {
  consecutive_recall_fail: "连续召回失败",
  manual_reassign: "人工重新分配",
  ownership_change: "归属变更",
};

const TransferLog: React.FC = () => {
  const [items, setItems] = useState<TransferLogItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [query, setQuery] = useState<TransferLogQuery>({ page: 1, page_size: 20 });

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const data = await fetchTransferLogs(query);
      setItems(data.items);
      setTotal(data.total);
    } catch {
      message.error("加载转移日志失败");
    } finally {
      setLoading(false);
    }
  }, [query]);

  useEffect(() => { load(); }, [load]);

  const columns: ColumnsType<TransferLogItem> = [
    {
      title: "转移时间", dataIndex: "created_at", key: "created_at", width: 160,
      render: (v: string) => formatTime(v),
    },
    {
      title: "门店", dataIndex: "site_name", key: "site_name", width: 120,
      render: (v: string, r) => v || `#${r.site_id}`,
    },
    {
      title: "客户", key: "member", width: 140,
      render: (_: unknown, r) => (
        <Tooltip title={`ID: ${r.member_id}`}>
          {r.member_name || `会员#${r.member_id}`}
        </Tooltip>
      ),
    },
    {
      title: "原助教", key: "from", width: 120,
      render: (_: unknown, r) => r.from_assistant_name || `#${r.from_assistant_id}`,
    },
    {
      title: "新助教", key: "to", width: 120,
      render: (_: unknown, r) => r.to_assistant_name || `#${r.to_assistant_id}`,
    },
    {
      title: "转移原因", dataIndex: "transfer_reason", key: "reason", width: 140,
      render: (v: string | null) => v ? (
        <Tag>{REASON_LABELS[v] || v}</Tag>
      ) : "—",
    },
    {
      title: "转移得分", dataIndex: "transfer_score", key: "score", width: 90,
      render: (v: number | null) => v != null ? v.toFixed(2) : "—",
    },
    {
      title: "保护检查", dataIndex: "guard_checks", key: "guards", width: 200,
      render: (v: Record<string, unknown> | null) => renderGuardChecks(v),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 16, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <Title level={4} style={{ margin: 0 }}>
          <SwapOutlined style={{ marginRight: 8 }} />
          客户转移日志
        </Title>
        <Button icon={<ReloadOutlined />} onClick={load} loading={loading}>刷新</Button>
      </div>

      <Card size="small" style={{ marginBottom: 16 }}>
        <Space wrap>
          <RangePicker
            placeholder={["开始日期", "结束日期"]}
            onChange={(dates) => {
              setQuery((q) => ({
                ...q,
                from_date: dates?.[0]?.format("YYYY-MM-DD"),
                to_date: dates?.[1]?.format("YYYY-MM-DD"),
                page: 1,
              }));
            }}
          />
          <InputNumber
            placeholder="助教 ID"
            style={{ width: 140 }}
            onChange={(v) => setQuery((q) => ({
              ...q,
              assistant_id: (v as number) ?? undefined,
              page: 1,
            }))}
          />
          <InputNumber
            placeholder="门店 ID"
            style={{ width: 140 }}
            onChange={(v) => setQuery((q) => ({
              ...q,
              site_id: (v as number) ?? undefined,
              page: 1,
            }))}
          />
        </Space>
      </Card>

      <Card size="small">
        <Table<TransferLogItem>
          rowKey="id"
          columns={columns}
          dataSource={items}
          loading={loading}
          size="small"
          scroll={{ x: 1200 }}
          pagination={{
            current: query.page,
            pageSize: query.page_size,
            total,
            showSizeChanger: true,
            showTotal: (t) => `共 ${t} 条`,
            onChange: (page, pageSize) => setQuery((q) => ({ ...q, page, page_size: pageSize })),
          }}
        />
      </Card>
    </div>
  );
};

export default TransferLog;
