import { Button, Card, Col, Form, Row, Select, Space, Table, Tag, Toast } from '@douyinfe/semi-ui';
import { IconCopy } from '@douyinfe/semi-icons';
import { useEffect, useState } from 'react';
import { api } from '../api/client';
import type { OpsHealth, QualitySummary, QualityIssueRow } from '../api/types';
import { PageHeader } from '../components/PageHeader';
import { qualityIssueLabel, qualityProtocolLabel, qualityProtocolOptions } from '../domain/qualityIssue';
import { qualityIssueVehicleLookup } from '../domain/vehicleLookup';

const statusColor: Record<string, 'green' | 'orange' | 'red' | 'grey'> = {
  ok: 'green',
  warning: 'orange',
  error: 'red'
};

function formatLag(value?: number | null) {
  return value == null ? '未接入' : value.toLocaleString();
}

function storageReadStatus(health: OpsHealth | null) {
  return health?.tdengineWritable && health.mysqlWritable ? 'ok' : 'error';
}

function formatRequestTimeout(health: OpsHealth | null) {
  const value = health?.runtime?.requestTimeoutMs;
  return value == null || value <= 0 ? '未限制' : `${value.toLocaleString()} ms`;
}

const emptySummary: QualitySummary = {
  issueVehicleCount: 0,
  issueRecordCount: 0,
  errorCount: 0,
  warningCount: 0,
  protocols: [],
  issueTypes: []
};

function qualityParams(values: Record<string, string>) {
  const params = new URLSearchParams();
  if (values?.keyword) params.set('keyword', values.keyword);
  if (values?.protocol) params.set('protocol', values.protocol);
  return params;
}

async function copyText(value: string, label: string) {
  const text = value.trim();
  if (!text) {
    Toast.warning(`${label}为空`);
    return;
  }
  try {
    await navigator.clipboard.writeText(text);
    Toast.success(`已复制${label}`);
  } catch {
    Toast.error(`复制${label}失败`);
  }
}

export function Quality({
  onOpenVehicle,
  onHealthLoaded
}: {
  onOpenVehicle: (vin: string) => void;
  onHealthLoaded?: (health: OpsHealth) => void;
}) {
  const [issues, setIssues] = useState<QualityIssueRow[]>([]);
  const [summary, setSummary] = useState<QualitySummary>(emptySummary);
  const [health, setHealth] = useState<OpsHealth | null>(null);
  const [loadingIssues, setLoadingIssues] = useState(true);
  const [loadingSummary, setLoadingSummary] = useState(true);
  const [loadingHealth, setLoadingHealth] = useState(true);
  const [filters, setFilters] = useState<Record<string, string>>({});
  const [pagination, setPagination] = useState({ currentPage: 1, pageSize: 20, total: 0 });

  const loadIssues = (values: Record<string, string> = filters, page = pagination.currentPage, pageSize = pagination.pageSize) => {
    setLoadingIssues(true);
    const params = qualityParams(values);
    params.set('limit', String(pageSize));
    params.set('offset', String((page - 1) * pageSize));
    api.qualityIssues(params)
      .then((nextPage) => {
        setIssues(nextPage.items);
        setPagination({ currentPage: page, pageSize, total: nextPage.total });
      })
      .catch((error: Error) => Toast.error(error.message))
      .finally(() => setLoadingIssues(false));
  };

  const loadSummary = (values: Record<string, string> = filters) => {
    setLoadingSummary(true);
    api.qualitySummary(qualityParams(values))
      .then(setSummary)
      .catch((error: Error) => Toast.error(error.message))
      .finally(() => setLoadingSummary(false));
  };

  const loadHealth = () => {
    setLoadingHealth(true);
    api.opsHealth()
      .then((nextHealth) => {
        setHealth(nextHealth);
        onHealthLoaded?.(nextHealth);
      })
      .catch((error: Error) => Toast.error(error.message))
      .finally(() => setLoadingHealth(false));
  };

  useEffect(() => {
    loadSummary({});
    loadIssues({}, 1, pagination.pageSize);
    loadHealth();
  }, []);

  return (
    <div className="vp-page">
      <PageHeader title="质量治理" description="围绕车辆服务排查断链、VIN 缺失、字段缺失和链路健康" />
      <div className="vp-kpi-grid">
        {[
          { label: '问题车辆', value: summary.issueVehicleCount.toLocaleString() },
          { label: '问题记录', value: summary.issueRecordCount.toLocaleString() },
          { label: '错误 / 警告', value: `${summary.errorCount}/${summary.warningCount}` },
          {
            label: '主要问题',
            value: summary.issueTypes.length > 0 ? `${qualityIssueLabel(summary.issueTypes[0].name)} ${summary.issueTypes[0].count}` : '-'
          }
        ].map((item) => (
          <Card key={item.label} bordered loading={loadingSummary}>
            <div className="vp-kpi-value">{item.value}</div>
            <div className="vp-kpi-label">{item.label}</div>
          </Card>
        ))}
      </div>
      <Row gutter={16}>
        <Col span={6}><Card bordered title="Kafka Lag">{formatLag(health?.kafkaLag)}</Card></Col>
        <Col span={6}><Card bordered title="Redis 在线 Key">{formatLag(health?.redisOnlineKeys)}</Card></Col>
        <Col span={6}><Card bordered title="BFF 请求超时">{formatRequestTimeout(health)}</Card></Col>
        <Col span={6}>
          <Card bordered title="存储读取">
            <Tag color={statusColor[storageReadStatus(health)]}>{storageReadStatus(health) === 'ok' ? '正常' : '异常'}</Tag>
          </Card>
        </Col>
      </Row>
      <Card bordered title="质量问题" style={{ marginTop: 16 }}>
        <Form layout="horizontal" onSubmit={(values) => {
          const nextFilters = values as Record<string, string>;
          setFilters(nextFilters);
          loadSummary(nextFilters);
          loadIssues(nextFilters, 1, pagination.pageSize);
        }} style={{ marginBottom: 12 }}>
          <Form.Input field="keyword" label="关键词" placeholder="VIN / 车牌 / 手机号 / 来源地址" style={{ width: 260 }} />
          <Form.Select field="protocol" label="数据来源" placeholder="全部来源" style={{ width: 160 }}>
            {qualityProtocolOptions.map((item) => (
              <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
            ))}
          </Form.Select>
          <Space>
            <Button htmlType="submit" theme="solid" type="primary">筛选</Button>
            <Button onClick={() => {
              setFilters({});
              loadSummary({});
              loadIssues({}, 1, pagination.pageSize);
            }}>重置</Button>
          </Space>
        </Form>
        <Table
          loading={loadingIssues}
          rowKey={(row?: QualityIssueRow) => `${row?.protocol ?? ''}-${row?.issueType ?? ''}-${row?.lastSeen ?? ''}-${row?.detail ?? ''}`}
          dataSource={issues}
          pagination={{
            currentPage: pagination.currentPage,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            onPageChange: (page) => loadIssues(filters, page, pagination.pageSize),
            onPageSizeChange: (pageSize) => loadIssues(filters, 1, pageSize)
          }}
          columns={[
            { title: 'VIN', dataIndex: 'vin' },
            { title: '车牌', dataIndex: 'plate' },
            { title: '手机号', dataIndex: 'phone' },
            { title: '来源地址', dataIndex: 'sourceEndpoint' },
            { title: '数据来源', render: (_: unknown, row: QualityIssueRow) => qualityProtocolLabel(row.protocol) },
            { title: '问题', render: (_: unknown, row: QualityIssueRow) => qualityIssueLabel(row.issueType) },
            { title: '级别', render: (_: unknown, row: QualityIssueRow) => <Tag color={row.severity === 'error' ? 'red' : 'orange'}>{row.severity}</Tag> },
            { title: '最后时间', dataIndex: 'lastSeen' },
            { title: '说明', dataIndex: 'detail' },
            {
              title: '操作',
              width: 250,
              render: (_: unknown, row: QualityIssueRow) => {
                const lookup = qualityIssueVehicleLookup(row);
                return (
                  <Space spacing={4}>
                    <Button size="small" icon={<IconCopy />} onClick={() => copyText(row.phone, '手机号')}>手机号</Button>
                    <Button size="small" icon={<IconCopy />} onClick={() => copyText(row.sourceEndpoint, '来源')}>来源</Button>
                    <Button size="small" disabled={!lookup.key} onClick={() => onOpenVehicle(lookup.key)}>
                      {lookup.label}
                    </Button>
                  </Space>
                );
              }
            }
          ]}
        />
      </Card>
      <Card
        bordered
        title={<Space><span>链路健康</span><Button size="small" loading={loadingHealth} onClick={loadHealth}>刷新链路</Button></Space>}
        style={{ marginTop: 16 }}
      >
        <Table
          loading={loadingHealth}
          dataSource={health?.linkHealth ?? []}
          pagination={false}
          columns={[
            { title: '链路', dataIndex: 'name' },
            {
              title: '状态',
              render: (_: unknown, row: { status: string }) => (
                <Tag color={statusColor[row.status] ?? 'grey'}>{row.status}</Tag>
              )
            },
            { title: '说明', dataIndex: 'detail' }
          ]}
        />
      </Card>
    </div>
  );
}
