import { Button, Card, Col, Form, Row, Select, Space, Table, Tag, Toast } from '@douyinfe/semi-ui';
import { useEffect, useState } from 'react';
import { api } from '../api/client';
import type { OpsHealth, QualityIssueRow } from '../api/types';
import { PageHeader } from '../components/PageHeader';

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

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

export function Quality() {
  const [issues, setIssues] = useState<QualityIssueRow[]>([]);
  const [health, setHealth] = useState<OpsHealth | null>(null);
  const [loadingIssues, setLoadingIssues] = 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 = new URLSearchParams({ limit: String(pageSize), offset: String((page - 1) * pageSize) });
    if (values?.keyword) params.set('keyword', values.keyword);
    if (values?.protocol) params.set('protocol', values.protocol);
    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));
  };

  useEffect(() => {
    loadIssues({}, 1, pagination.pageSize);
    api.opsHealth()
      .then(setHealth)
      .catch((error: Error) => Toast.error(error.message));
  }, []);

  return (
    <div className="vp-page">
      <PageHeader title="数据质量" description="断链、VIN 缺失、字段缺失和链路健康的排查入口" />
      <Row gutter={16}>
        <Col span={8}><Card bordered title="Kafka Lag">{formatLag(health?.kafkaLag)}</Card></Col>
        <Col span={8}><Card bordered title="Redis 在线 Key">{formatLag(health?.redisOnlineKeys)}</Card></Col>
        <Col span={8}><Card bordered title="存储写入">{health?.tdengineWritable && health.mysqlWritable ? '正常' : '异常'}</Card></Col>
      </Row>
      <Card bordered title="质量问题" style={{ marginTop: 16 }}>
        <Form layout="horizontal" onSubmit={(values) => {
          const nextFilters = values as Record<string, string>;
          setFilters(nextFilters);
          loadIssues(nextFilters, 1, pagination.pageSize);
        }} style={{ marginBottom: 12 }}>
          <Form.Input field="keyword" label="关键词" placeholder="手机号 / 来源地址 / 车牌" style={{ width: 240 }} />
          <Form.Select field="protocol" label="协议" placeholder="全部协议" style={{ width: 160 }}>
            <Select.Option value="JT808">JT808</Select.Option>
          </Form.Select>
          <Space>
            <Button htmlType="submit" theme="solid" type="primary">筛选</Button>
            <Button onClick={() => {
              setFilters({});
              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: 'protocol' },
            { title: '问题', dataIndex: 'issueType' },
            { title: '级别', render: (_: unknown, row: QualityIssueRow) => <Tag color={row.severity === 'error' ? 'red' : 'orange'}>{row.severity}</Tag> },
            { title: '最后时间', dataIndex: 'lastSeen' },
            { title: '说明', dataIndex: 'detail' }
          ]}
        />
      </Card>
      <Card bordered title="链路健康" style={{ marginTop: 16 }}>
        <Table
          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>
  );
}
