import { IconChevronRight, IconClose } from '@douyinfe/semi-icons';
import { Button, Card, Tag } from '@douyinfe/semi-ui';
import { useState } from 'react';
import { Link } from 'react-router-dom';
import type { VehicleRealtimeRow } from '../../api/types';
import { formatNumber, relativeFreshness, statusLabel, vehicleStatus } from '../domain/monitor';
import { protocolSourceLabel } from '../domain/protocols';
import { formatTelemetryValue } from '../domain/telemetry';
import { useMonitorVehicleCard } from '../hooks/useMonitorData';
import { withMonitorReturn } from '../routing/monitorContext';
import { ProtocolTag } from '../shared/ProtocolTag';
import { VehicleSourceEvidencePanel } from '../shared/VehicleSourceEvidencePanel';
import { WorkspacePanelHeader } from '../shared/WorkspacePanelHeader';

function hasRealtimeLocation(vehicle: VehicleRealtimeRow) {
  if (vehicle.locationAvailable != null) return vehicle.locationAvailable;
  return Number.isFinite(vehicle.longitude) && Number.isFinite(vehicle.latitude)
    && Math.abs(vehicle.longitude) <= 180 && Math.abs(vehicle.latitude) <= 90
    && (vehicle.longitude !== 0 || vehicle.latitude !== 0);
}

function hasRealtimeSpeed(vehicle: VehicleRealtimeRow) {
  return vehicle.speedAvailable ?? hasRealtimeLocation(vehicle);
}

function hasRealtimeMileage(vehicle: VehicleRealtimeRow) {
  return vehicle.mileageAvailable ?? hasRealtimeLocation(vehicle);
}

function hasRealtimeSOC(vehicle: VehicleRealtimeRow) {
  return vehicle.socAvailable ?? (vehicle.primaryProtocol === 'GB32960' || vehicle.primaryProtocol === 'YUTONG_MQTT');
}

export default function MonitorVehicleDetailCard({
  vehicle,
  monitorReturn,
  onCollapse,
  onClear
}: {
  vehicle: VehicleRealtimeRow;
  monitorReturn: string;
  onCollapse: () => void;
  onClear: () => void;
}) {
  const [sourceEvidenceOpen, setSourceEvidenceOpen] = useState(false);
  const card = useMonitorVehicleCard(vehicle.vin, vehicle, true);
  const detail = card.detail.data;
  const activeAlerts = card.activeAlerts.data;
  const telemetry = card.telemetry?.data;
  const address = card.address.data;
  const status = vehicleStatus(vehicle);
  // The realtime row is joined to vehicle_daily_mileage with stat_date = CURDATE().
  // Vehicle detail mileage is ordered by recency and may start with yesterday, so it
  // must never be used as a fallback for a metric explicitly labelled "今日里程".
  const dailyMileage = vehicle.todayMileageAvailable === true ? vehicle.todayMileageKm : undefined;
  const latestAlert = activeAlerts?.items[0];
  const mileageLabel = vehicle.primaryProtocol === 'JT808' ? 'GPS 总里程' : '仪表盘总里程';
  const encodedVin = encodeURIComponent(vehicle.vin);
  const accessSource = detail?.profile?.accessProvider || vehicle.locationSource;
  const accessSourceLabel = protocolSourceLabel(accessSource) || '来源待补充';
  const availableProtocols = detail?.sources?.length ? detail.sources : vehicle.protocols;
  const workflowLinks = [
    ['单车详情', `/vehicles/${encodedVin}`],
    ['轨迹回放', `/tracks?vin=${encodedVin}`],
    ['历史数据', `/history?vin=${encodedVin}`],
    ['里程查询', `/statistics?vins=${encodedVin}`]
  ] as const;
  const gbHighlights = (telemetry?.values ?? []).filter((item) => item.protocol === 'GB32960' && [
    'fuel_cell_voltage_v', 'fuel_cell_current_a', 'hydrogen_consumption_kg_per_100km',
    'hydrogen_concentration_percent', 'hydrogen_pressure_mpa', 'hydrogen_temperature_c',
    'engine_speed_rpm', 'total_voltage_v', 'total_current_a'
  ].includes(item.key)).slice(0, 9);

  return <Card className="v2-vehicle-detail" bodyStyle={{ padding: 0 }}>
    <div className="v2-detail-body" role="region" aria-label={`${vehicle.plate || vehicle.vin}车辆详情`}>
      <div className="v2-detail-shell-header">
        <div className="v2-detail-controls">
          <Button size="small" theme="light" type="tertiary" icon={<IconChevronRight />} aria-label="收起车辆详情" title="收起到地图右侧" onClick={onCollapse} />
          <Button size="small" theme="light" type="danger" icon={<IconClose />} aria-label="取消选择车辆" title="取消选择车辆" onClick={onClear} />
        </div>
        <div className="v2-detail-title">
          <div><strong>{vehicle.plate || '未绑定车牌'}</strong><Tag className={`v2-status-text is-${status}`} color={status === 'driving' ? 'blue' : status === 'idle' || status === 'online' ? 'green' : status === 'alert' ? 'red' : 'grey'} type="light" size="small">{statusLabel(status)}</Tag></div>
          <small>{vehicle.vin}</small>
        </div>
        <nav className="v2-detail-actions" aria-label="车辆快捷操作">
          {workflowLinks.map(([label, path]) => <Link key={label} to={withMonitorReturn(path, monitorReturn)}><span>{label}</span><IconChevronRight aria-hidden="true" /></Link>)}
        </nav>
      </div>
      <section className="v2-detail-section v2-detail-report">
        <WorkspacePanelHeader
          variant="compact"
          title="最新上报"
          description="平台最新接收证据"
          meta={<Tag color={vehicle.online ? 'green' : 'grey'} type="light" size="small">{relativeFreshness(vehicle.lastSeen)}</Tag>}
        />
        <div className="v2-report-summary">
          <span className="is-time" title={vehicle.lastSeen || '暂无上报'}><small>平台接收时间</small><strong>{vehicle.lastSeen || '暂无上报'}</strong></span>
          <span className="is-protocol" title={vehicle.primaryProtocol || '未知协议'}><small>主协议</small><ProtocolTag protocol={vehicle.primaryProtocol} compact unknownLabel="未知协议" /></span>
          <span className="is-source" title={accessSource || '来源待补充'}><small>接入来源</small><b>{accessSourceLabel}</b></span>
        </div>
        <dl className="v2-detail-list">
          <div><dt>坐标</dt><dd><Button theme="borderless" type="tertiary" className="v2-detail-source-link" aria-label="查看全部位置来源" title="展开全部位置来源" onClick={() => setSourceEvidenceOpen(true)}>{hasRealtimeLocation(vehicle) ? `${vehicle.longitude.toFixed(6)}, ${vehicle.latitude.toFixed(6)}` : '—'}</Button></dd></div>
          <div><dt>位置</dt><dd>{hasRealtimeLocation(vehicle) ? address?.formattedAddress || '位置解析中' : '暂无实时位置'}</dd></div>
        </dl>
      </section>
      <section className="v2-detail-section">
        <WorkspacePanelHeader
          variant="compact"
          title="实时状态"
          description={accessSourceLabel}
          meta={<ProtocolTag protocol={vehicle.primaryProtocol} compact unknownLabel="未知协议" />}
        />
        <div className="v2-metric-grid">
          <div className="is-speed"><small>速度</small><strong>{hasRealtimeSpeed(vehicle) ? formatNumber(vehicle.speedKmh, 1) : '—'}<em>{hasRealtimeSpeed(vehicle) ? 'km/h' : ''}</em></strong></div>
          <div className="is-soc"><small>SOC</small><strong>{hasRealtimeSOC(vehicle) ? formatNumber(vehicle.socPercent, 1) : '—'}<em>{hasRealtimeSOC(vehicle) ? '%' : ''}</em></strong></div>
          <div className="is-mileage"><small>{mileageLabel}</small><Button theme="borderless" type="tertiary" className="v2-metric-source-link" aria-label="查看总里程全部来源" title="展开全部里程来源" onClick={() => setSourceEvidenceOpen(true)}><span>{hasRealtimeMileage(vehicle) ? formatNumber(vehicle.totalMileageKm, 1) : '—'}<em>{hasRealtimeMileage(vehicle) ? 'km' : ''}</em></span><IconChevronRight /></Button></div>
          <div className="is-today"><small>今日里程</small><Button theme="borderless" type="tertiary" className="v2-metric-source-link" aria-label="查看今日里程全部来源" title="展开全部里程来源" onClick={() => setSourceEvidenceOpen(true)}><span>{dailyMileage == null ? '—' : formatNumber(dailyMileage, 1)}<em>{dailyMileage == null ? '' : 'km'}</em></span><IconChevronRight /></Button></div>
          <div className="is-status"><small>状态</small><strong>{statusLabel(status)}</strong></div>
          <div className={`is-alert${(activeAlerts?.total ?? 0) > 0 ? ' has-alerts' : ''}`}><small>当前告警</small><strong>{formatNumber(activeAlerts?.total ?? 0)}<em>条</em></strong></div>
        </div>
        {gbHighlights.length ? <div className="v2-gb-highlight-grid">{gbHighlights.map((item) => <div key={`${item.key}-${item.sourceField}`} title={item.description}><small>{item.label}</small><strong>{formatTelemetryValue(item.value, item.displayValue)}<em>{item.unit}</em></strong></div>)}</div> : null}
      </section>
      <section className="v2-detail-section">
        <WorkspacePanelHeader
          variant="compact"
          title="车辆信息"
          description="身份、车型与来源覆盖"
          meta={<Tag color={vehicle.onlineSourceCount ? 'green' : 'grey'} type="light" size="small">{vehicle.onlineSourceCount}/{vehicle.sourceCount} 在线</Tag>}
        />
        <dl className="v2-detail-list">
          <div><dt>VIN</dt><dd>{vehicle.vin}</dd></div>
          <div><dt>品牌 / 车型</dt><dd>{[detail?.profile?.brandName, detail?.profile?.modelName].filter(Boolean).join(' / ') || vehicle.oem || '待补充'}</dd></div>
          <div><dt>可用协议</dt><dd className="v2-detail-protocols">{availableProtocols.length ? availableProtocols.map((protocol) => <ProtocolTag key={protocol} protocol={protocol} compact />) : <ProtocolTag compact unknownLabel="未知协议" />}</dd></div>
          <div><dt>接入供应商</dt><dd>{detail?.profile?.accessProvider || '待补充'}</dd></div>
          <div><dt>来源覆盖</dt><dd>{vehicle.onlineSourceCount}/{vehicle.sourceCount}</dd></div>
          <div><dt>告警状态</dt><dd>{latestAlert ? `${latestAlert.ruleName} · ${latestAlert.severity}` : '无当前业务告警'}</dd></div>
        </dl>
      </section>
      <VehicleSourceEvidencePanel vin={vehicle.vin} compact open={sourceEvidenceOpen} onOpenChange={setSourceEvidenceOpen} />
    </div>
  </Card>;
}
