import React from 'react';
import { X } from 'lucide-react';
import type { VehicleRecord } from '../types';
import {
  buildMapEmbedUrl,
  formatGpsTime,
  resolveGpsLocationAddress,
  resolveVehicleGpsCoords,
} from '../utils/vehicle';

interface LocationMapModalProps {
  open: boolean;
  record: VehicleRecord | null;
  onClose: () => void;
}

export function LocationMapModal({ open, record, onClose }: LocationMapModalProps) {
  if (!open || !record) return null;

  const coords = resolveVehicleGpsCoords(record);
  const address = resolveGpsLocationAddress(record);
  if (!coords) return null;

  const mapUrl = buildMapEmbedUrl(coords.lat, coords.lng);

  return (
    <div className="vm-modal-backdrop" role="presentation" onClick={onClose}>
      <div
        className="vm-modal vm-modal-map"
        role="dialog"
        aria-modal="true"
        aria-labelledby="vm-location-map-title"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="vm-modal-header">
          <div>
            <h2 id="vm-location-map-title">车辆定位</h2>
            <p>{record.plateNo} · {address}</p>
          </div>
          <button type="button" className="vm-modal-close" onClick={onClose} aria-label="关闭">
            <X size={18} aria-hidden />
          </button>
        </header>
        <div className="vm-location-map-body">
          <div className="vm-location-map-frame-wrap">
            <iframe
              className="vm-location-map-frame"
              title={`${record.plateNo} 当前定位地图`}
              src={mapUrl}
              loading="lazy"
              referrerPolicy="no-referrer-when-downgrade"
            />
            <span className="vm-location-map-marker" aria-hidden />
          </div>
          <p className="vm-location-map-gps-time">
            GPS最后更新时间：{formatGpsTime(record.gpsTime)}
          </p>
        </div>
      </div>
    </div>
  );
}
