import { useState } from 'react';
import { Button, Descriptions, Drawer, Form, Input, Select, Table, Tag, Typography } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { request } from '../lib/api';
import { fmtTime } from '../lib/constants';
import {
  THIRD_PARTY_PROVIDER_LABELS,
  THIRD_PARTY_SCENE_LABELS,
  THIRD_PARTY_STATUS_LABELS,
  formatRef,
  zhLabel,
} from '../lib/display-labels';
import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';


type Row = {
  id: string;
  provider: string;
  scene: string;
  refType: string | null;
  refId: string | null;
  requestUrl?: string | null;
  requestBody?: Record<string, unknown> | null;
  responseBody?: Record<string, unknown> | null;
  externalNo?: string | null;
  amount?: string | null;
  status: string;
  errorMessage?: string | null;
  createdAt: string;
};

const PROVIDER_OPTIONS = [
  { value: 'WECHAT_AUTH', label: '微信授权' },
  { value: 'WECHAT_PAY', label: '微信支付' },
  { value: 'WECHAT_MAP', label: '微信/腾讯地图' },
  { value: 'ALIYUN_OSS', label: '阿里云 OSS' },
  { value: 'ALIYUN_SMS', label: '阿里云短信' },
  { value: 'MOCK_SMS', label: 'Mock 短信' },
  { value: 'XFX', label: '小飞侠' },
  { value: 'LOGISTICS', label: '物流快递' },
];

const STATUS_COLOR: Record<string, string> = {
  SUCCESS: 'success',
  FAILED: 'error',
  PENDING: 'processing',
};

function summarizeJson(json: Record<string, unknown> | null | undefined) {
  if (!json || Object.keys(json).length === 0) return '—';
  const text = JSON.stringify(json);
  return text.length > 60 ? `${text.slice(0, 60)}…` : text;
}

function JsonBlock({ value }: { value: unknown }) {
  if (value == null) return <span>—</span>;
  return (
    <pre style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-all', fontSize: 12 }}>
      {JSON.stringify(value, null, 2)}
    </pre>
  );
}

export default function ThirdPartyLogsPage() {
  const [filters, setFilters] = useState<Record<string, string>>({});
  const { data, loading, page, pageSize, setPage, setPageSize } = useAdminList<Row>(
    '/common/third-party-logs',
    () => {
      const qs = new URLSearchParams();
      if (filters.provider) qs.set('provider', filters.provider);
      if (filters.scene) qs.set('scene', filters.scene);
      if (filters.refId) qs.set('refId', filters.refId);
      return qs;
    },
    [filters],
  );
  const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
  const [drawerOpen, setDrawerOpen] = useState(false);

  const baseColumns: ColumnsType<Row> = [
    { title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
    { title: '渠道', dataIndex: 'provider', width: 120, render: (v: string) => zhLabel(THIRD_PARTY_PROVIDER_LABELS, v) },
    { title: '场景', dataIndex: 'scene', width: 140, render: (v: string) => zhLabel(THIRD_PARTY_SCENE_LABELS, v) },
    {
      title: '关联',
      width: 120,
      render: (_, r) => formatRef(r.refType, r.refId),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 90,
      render: (v: string) => <Tag color={STATUS_COLOR[v] ?? 'default'}>{zhLabel(THIRD_PARTY_STATUS_LABELS, v)}</Tag>,
    },
    {
      title: '错误信息',
      dataIndex: 'errorMessage',
      render: (v: string | null | undefined) => v || '—',
    },
    {
      title: '请求摘要',
      render: (_, r) => summarizeJson(r.requestBody),
    },
    {
      title: '外部单号',
      dataIndex: 'externalNo',
      width: 140,
      render: (v, row) => (
        <AdminPrimaryLink
          onClick={async () => {
            setDetail(await request(`/common/third-party-logs/${row.id}`));
            setDrawerOpen(true);
          }}
        >
          {v}
        </AdminPrimaryLink>
      ),
    },
    {
      title: '操作',
      width: 80,
      render: (_, row) => (
        <Button
          type="link"
          size="small"
          onClick={async () => {
            setDetail(await request(`/common/third-party-logs/${row.id}`));
            setDrawerOpen(true);
          }}
        >
          详情
        </Button>
      ),
    },
  ];

  const { columns, settingsButton, settingsModal } = useAdminListColumns('logs-third-party', baseColumns, {
    page,
    pageSize,
  });

  return (
    <div>
      {settingsModal}
      <AdminListHeader title="第三方日志" settings={settingsButton} />
      <Form
        layout="inline"
        style={{ marginBottom: 16 }}
        onFinish={(v) => {
          setFilters(v);
          setPage(1);
        }}
      >
        <Form.Item name="provider" label="渠道">
          <Select allowClear placeholder="全部" style={{ width: 160 }} options={PROVIDER_OPTIONS} />
        </Form.Item>
        <Form.Item name="scene" label="场景">
          <Input allowClear placeholder="场景编码" style={{ width: 160 }} />
        </Form.Item>
        <Form.Item name="refId" label="关联ID">
          <Input allowClear style={{ width: 120 }} />
        </Form.Item>
        <Button type="primary" htmlType="submit">
          筛选
        </Button>
      </Form>
      <Table
        rowKey="id"
        loading={loading}
        columns={columns}
        dataSource={data?.items ?? []}
        scroll={{ x: 'max-content' }}
        pagination={{
          current: page,
          pageSize,
          total: data?.total ?? 0,
          showSizeChanger: true,
          onChange: (p, ps) => {
            setPage(p);
            setPageSize(ps);
          },
        }}
      />
      <Drawer title="第三方日志详情" width={640} open={drawerOpen} onClose={() => setDrawerOpen(false)}>
        {detail && (
          <Descriptions column={1} bordered size="small">
            <Descriptions.Item label="ID">{String(detail.id)}</Descriptions.Item>
            <Descriptions.Item label="渠道">{zhLabel(THIRD_PARTY_PROVIDER_LABELS, String(detail.provider))}</Descriptions.Item>
            <Descriptions.Item label="场景">{zhLabel(THIRD_PARTY_SCENE_LABELS, String(detail.scene))}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={STATUS_COLOR[String(detail.status)] ?? 'default'}>
                {zhLabel(THIRD_PARTY_STATUS_LABELS, String(detail.status))}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="关联">
              {formatRef(detail.refType ? String(detail.refType) : null, detail.refId ? String(detail.refId) : null)}
            </Descriptions.Item>
            <Descriptions.Item label="外部单号">{String(detail.externalNo ?? '—')}</Descriptions.Item>
            <Descriptions.Item label="金额">{detail.amount != null ? String(detail.amount) : '—'}</Descriptions.Item>
            <Descriptions.Item label="请求 URL">{String(detail.requestUrl ?? '—')}</Descriptions.Item>
            <Descriptions.Item label="错误信息">
              {detail.errorMessage ? (
                <Typography.Text type="danger" style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
                  {String(detail.errorMessage)}
                </Typography.Text>
              ) : (
                '—'
              )}
            </Descriptions.Item>
            <Descriptions.Item label="时间">{fmtTime(String(detail.createdAt))}</Descriptions.Item>
            <Descriptions.Item label="请求体">
              <JsonBlock value={detail.requestBody} />
            </Descriptions.Item>
            <Descriptions.Item label="响应体">
              <JsonBlock value={detail.responseBody} />
            </Descriptions.Item>
          </Descriptions>
        )}
      </Drawer>
    </div>
  );
}
