import { Button, Card, Col, Form, Row, Select, Space, Spin, Table, Tag, Toast, Typography } from '@douyinfe/semi-ui';
import { useEffect, useState } from 'react';
import { api } from '../api/client';
import type { DashboardSummary, LinkHealth, ProtocolStat, QualityIssueRow, VehicleCoverageRow, VehicleRealtimeRow, VehicleRow } from '../api/types';
import { PageHeader } from '../components/PageHeader';
import { StatusTag } from '../components/StatusTag';

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 Dashboard({ onOpenVehicle, onOpenQuality }: { onOpenVehicle: (vin: string) => void; onOpenQuality: () => void }) {
  const [summary, setSummary] = useState<DashboardSummary | null>(null);
  const [vehicles, setVehicles] = useState<VehicleRow[]>([]);
  const [coverage, setCoverage] = useState<VehicleCoverageRow[]>([]);
  const [locations, setLocations] = useState<VehicleRealtimeRow[]>([]);
  const [qualityIssues, setQualityIssues] = useState<QualityIssueRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [coverageLoading, setCoverageLoading] = useState(false);

  const loadCoverage = (values?: Record<string, string>) => {
    setCoverageLoading(true);
    const params = new URLSearchParams({ limit: '8' });
    if (values?.keyword) params.set('keyword', values.keyword);
    if (values?.coverage) params.set('coverage', values.coverage);
    if (values?.online) params.set('online', values.online);
    if (values?.bindingStatus) params.set('bindingStatus', values.bindingStatus);
    api.vehicleCoverage(params)
      .then((page) => setCoverage(page.items))
      .catch((error: Error) => Toast.error(error.message))
      .finally(() => setCoverageLoading(false));
  };

  useEffect(() => {
    Promise.all([
      api.dashboardSummary(),
      api.vehicles(new URLSearchParams({ limit: '5' })),
      api.vehicleCoverage(new URLSearchParams({ limit: '8' })),
      api.vehicleRealtime(new URLSearchParams({ limit: '8' })),
      api.qualityIssues(new URLSearchParams({ limit: '5' }))
    ])
      .then(([nextSummary, vehiclePage, coveragePage, locationPage, qualityPage]) => {
        setSummary(nextSummary);
        setVehicles(vehiclePage.items);
        setCoverage(coveragePage.items);
        setLocations(locationPage.items);
        setQualityIssues(qualityPage.items);
      })
      .catch((error: Error) => Toast.error(error.message))
      .finally(() => setLoading(false));
  }, []);

  const kpis = [
    { label: '在线车辆', value: summary?.onlineVehicles ?? 0 },
    { label: '今日活跃', value: summary?.activeToday ?? 0 },
    { label: '今日帧数', value: summary?.frameToday.toLocaleString() ?? '0' },
    { label: '质量问题', value: summary?.issueVehicles ?? 0 }
  ];

  return (
    <div className="vp-page">
      <PageHeader title="总览工作台" description="车辆在线、协议分布、数据质量和链路健康的统一入口" />
      <Spin spinning={loading}>
        <div className="vp-kpi-grid">
          {kpis.map((item) => (
            <Card key={item.label} bordered>
              <div className="vp-kpi-value">{item.value}</div>
              <div className="vp-kpi-label">{item.label}</div>
            </Card>
          ))}
        </div>
        <Row gutter={16}>
          <Col span={14}>
            <Card title="协议在线分布" bordered>
              <Table
                pagination={false}
                dataSource={summary?.protocols ?? []}
                columns={[
                  { title: '协议', dataIndex: 'protocol' },
                  { title: '在线', dataIndex: 'online' },
                  { title: '总数', dataIndex: 'total' },
                  {
                    title: '在线率',
                    render: (_: unknown, row: ProtocolStat) => `${Math.round((row.online / row.total) * 100)}%`
                  }
                ]}
              />
            </Card>
          </Col>
          <Col span={10}>
            <Card title="链路健康" bordered>
              <Table
                pagination={false}
                dataSource={summary?.linkHealth ?? []}
                columns={[
                  { title: '链路', dataIndex: 'name' },
                  {
                    title: '状态',
                    render: (_: unknown, row: LinkHealth) => <Tag color={statusColor[row.status] ?? 'grey'}>{row.status}</Tag>
                  },
                  { title: '说明', dataIndex: 'detail' }
                ]}
              />
            </Card>
          </Col>
        </Row>
        <Card title="实时积压" bordered style={{ marginTop: 16 }}>
          <Typography.Text>Kafka 当前消费积压：{formatLag(summary?.kafkaLag)}</Typography.Text>
        </Card>
        <Card
          title={<Space><span>质量问题预览</span><Button size="small" onClick={onOpenQuality}>查看全部</Button></Space>}
          bordered
          style={{ marginTop: 16 }}
        >
          <Table
            pagination={false}
            rowKey={(row?: QualityIssueRow) => `${row?.protocol ?? ''}-${row?.issueType ?? ''}-${row?.lastSeen ?? ''}-${row?.detail ?? ''}`}
            dataSource={qualityIssues}
            columns={[
              { title: 'VIN', dataIndex: 'vin', width: 160 },
              { title: '车牌', dataIndex: 'plate', width: 110 },
              { title: '来源', dataIndex: 'protocol', width: 110 },
              { title: '问题', dataIndex: 'issueType', width: 140 },
              { title: '级别', width: 90, render: (_: unknown, row: QualityIssueRow) => <Tag color={row.severity === 'error' ? 'red' : 'orange'}>{row.severity}</Tag> },
              { title: '最后时间', dataIndex: 'lastSeen', width: 170 },
              { title: '说明', dataIndex: 'detail' }
            ]}
          />
        </Card>
        <Card title="车辆服务覆盖" bordered style={{ marginTop: 16 }}>
          <Form layout="horizontal" onSubmit={(values) => loadCoverage(values as Record<string, string>)} style={{ marginBottom: 12 }}>
            <Form.Input field="keyword" label="关键词" placeholder="VIN / 车牌 / 手机号 / OEM" style={{ width: 240 }} />
            <Form.Select field="coverage" label="来源覆盖" placeholder="全部" style={{ width: 130 }}>
              <Select.Option value="single">单源</Select.Option>
              <Select.Option value="multi">多源</Select.Option>
            </Form.Select>
            <Form.Select field="online" label="在线" placeholder="全部" style={{ width: 130 }}>
              <Select.Option value="online">在线</Select.Option>
              <Select.Option value="offline">离线</Select.Option>
            </Form.Select>
            <Form.Select field="bindingStatus" label="绑定" placeholder="全部" style={{ width: 130 }}>
              <Select.Option value="bound">已绑定</Select.Option>
              <Select.Option value="unbound">未绑定</Select.Option>
            </Form.Select>
            <Space>
              <Button htmlType="submit" theme="solid" type="primary">筛选</Button>
              <Button onClick={() => loadCoverage()}>重置</Button>
            </Space>
          </Form>
          <Table
            loading={coverageLoading}
            pagination={false}
            rowKey="vin"
            dataSource={coverage}
            columns={[
              { title: '车牌', dataIndex: 'plate', width: 110 },
              { title: 'VIN', dataIndex: 'vin', width: 190 },
              {
                title: '来源',
                width: 240,
                render: (_: unknown, row: VehicleCoverageRow) => (
                  <Space spacing={4} wrap>
                    {row.protocols.map((protocol) => <Tag key={protocol} color="blue">{protocol}</Tag>)}
                  </Space>
                )
              },
              {
                title: '覆盖',
                width: 110,
                render: (_: unknown, row: VehicleCoverageRow) => `${row.onlineSourceCount}/${row.sourceCount}`
              },
              { title: '在线', width: 90, render: (_: unknown, row: VehicleCoverageRow) => <StatusTag status={row.online ? 'ok' : 'offline'} /> },
              { title: '绑定', width: 90, render: (_: unknown, row: VehicleCoverageRow) => <Tag color={row.bindingStatus === 'bound' ? 'green' : 'orange'}>{row.bindingStatus === 'bound' ? '已绑定' : '未绑定'}</Tag> },
              { title: '最后时间', dataIndex: 'lastSeen', width: 170 },
              { title: '操作', width: 110, render: (_: unknown, row: VehicleCoverageRow) => <Button onClick={() => onOpenVehicle(row.vin)}>车辆服务</Button> }
            ]}
          />
        </Card>
        <Row gutter={16} style={{ marginTop: 16 }}>
          <Col span={12}>
            <Card title="实时位置预览" bordered>
              <div className="vp-map" style={{ height: 260 }}>
                {locations.map((row, index) => (
                  <span
                    key={row.vin}
                    className="vp-map-dot"
                    title={`${row.plate} ${row.primaryProtocol}`}
                    style={{ left: `${18 + index * 13}%`, top: `${24 + (index % 4) * 15}%` }}
                  />
                ))}
              </div>
            </Card>
          </Col>
          <Col span={12}>
            <Card title="最新车辆" bordered>
              <Table
                pagination={false}
                dataSource={vehicles}
                columns={[
                  { title: '车牌', dataIndex: 'plate' },
                  { title: 'VIN', dataIndex: 'vin' },
                  { title: '协议', dataIndex: 'protocol' },
                  { title: '最后时间', dataIndex: 'lastSeen' }
                ]}
              />
            </Card>
          </Col>
        </Row>
      </Spin>
    </div>
  );
}
