import { Card, Table, Tabs, Toast } from '@douyinfe/semi-ui';
import { useEffect, useState } from 'react';
import { api } from '../api/client';
import type { RealtimeLocationRow } from '../api/types';
import { DataEmpty } from '../components/DataEmpty';
import { PageHeader } from '../components/PageHeader';

export function Realtime() {
  const [rows, setRows] = useState<RealtimeLocationRow[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.realtimeLocations(new URLSearchParams({ limit: '50' }))
      .then((page) => setRows(page.items))
      .catch((error: Error) => Toast.error(error.message))
      .finally(() => setLoading(false));
  }, []);

  return (
    <div className="vp-page">
      <PageHeader title="实时状态" description="按协议和车辆查看最新实时位置、在线状态和核心数据" />
      <Card bordered>
        <Tabs type="line">
          <Tabs.TabPane tab="表格视图" itemKey="table">
            {rows.length === 0 && !loading ? (
              <DataEmpty />
            ) : (
              <Table
                loading={loading}
                rowKey="vin"
                dataSource={rows}
                pagination={false}
                columns={[
                  { title: 'VIN', dataIndex: 'vin' },
                  { title: '车牌', dataIndex: 'plate' },
                  { title: '协议', dataIndex: 'protocol' },
                  { title: '速度 km/h', dataIndex: 'speedKmh' },
                  { title: 'SOC %', dataIndex: 'socPercent' },
                  { title: '总里程 km', dataIndex: 'totalMileageKm' },
                  { title: '最后时间', dataIndex: 'lastSeen' }
                ]}
              />
            )}
          </Tabs.TabPane>
          <Tabs.TabPane tab="地图视图" itemKey="map">
            <div className="vp-map">
              {rows.map((row, index) => (
                <span
                  key={row.vin}
                  className="vp-map-dot"
                  title={`${row.plate} ${row.protocol}`}
                  style={{ left: `${18 + index * 24}%`, top: `${26 + (index % 3) * 18}%` }}
                />
              ))}
            </div>
          </Tabs.TabPane>
        </Tabs>
      </Card>
    </div>
  );
}
