/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * Rider telemetry panel — displays GPS location, signal strength, battery,
 * and other real-time metrics for the selected rider. Integrated into the
 * dispatch sidebar when a rider card is focused.
 */

import React from 'react';
import { MapPin, Zap, Signal, Clock, Gauge } from 'lucide-react';
import { type Row } from '../services/fiestaApi';

interface RiderTelemetryPanelProps {
  logs: Row[];
  riderName?: string;
  isLoading?: boolean;
}

export default function RiderTelemetryPanel({ logs, riderName, isLoading }: RiderTelemetryPanelProps) {
  if (isLoading) {
    return (
      <div className="rider-telemetry-panel">
        <div className="rtm-header">Telemetry</div>
        <div className="rtm-loading">Loading GPS data…</div>
      </div>
    );
  }

  if (!logs || logs.length === 0) {
    return (
      <div className="rider-telemetry-panel">
        <div className="rtm-header">Telemetry</div>
        <div className="rtm-empty">No GPS telemetry available</div>
      </div>
    );
  }

  // Get the latest (most recent) GPS log
  const latest = logs[logs.length - 1];
  const lat = latest?.latitude || latest?.lat;
  const lon = latest?.longitude || latest?.lng;
  const battery = latest?.batterypercentage || latest?.battery;
  const signal = latest?.signalstrength || latest?.signal;
  const speed = latest?.speed || 0;
  const timestamp = latest?.logdate || latest?.timestamp;

  const getSignalBars = (signal: number | null) => {
    if (!signal) return 0;
    const s = Number(signal);
    if (s <= -120) return 1;
    if (s <= -100) return 2;
    if (s <= -80) return 3;
    if (s <= -60) return 4;
    return 5;
  };

  const bars = getSignalBars(signal ? Number(signal) : null);
  const batteryPercent = battery ? Number(battery) : null;

  return (
    <div className="rider-telemetry-panel">
      <div className="rtm-header">
        Telemetry
        {riderName && <span className="rtm-rider-name">{riderName}</span>}
      </div>

      <div className="rtm-grid">
        {/* GPS Location */}
        {lat && lon && (
          <div className="rtm-item rtm-gps">
            <div className="rtm-icon">
              <MapPin size={14} />
            </div>
            <div className="rtm-content">
              <div className="rtm-label">Location</div>
              <div className="rtm-value">{Number(lat).toFixed(4)}, {Number(lon).toFixed(4)}</div>
              <a
                href={`https://maps.google.com/?q=${lat},${lon}`}
                target="_blank"
                rel="noopener noreferrer"
                className="rtm-link"
              >
                View on Maps
              </a>
            </div>
          </div>
        )}

        {/* Signal Strength */}
        {signal && (
          <div className="rtm-item rtm-signal">
            <div className="rtm-icon">
              <Signal size={14} />
            </div>
            <div className="rtm-content">
              <div className="rtm-label">Signal</div>
              <div className="rtm-value">
                <span className="rtm-bars">
                  {[...Array(5)].map((_, i) => (
                    <span
                      key={i}
                      className={`bar ${i < bars ? 'active' : ''}`}
                      style={{
                        height: `${(i + 1) * 20}%`,
                        background: bars - i <= 1 ? '#ef4444' : bars - i <= 2 ? '#f59e0b' : '#22c55e',
                      }}
                    />
                  ))}
                </span>
                <span className="rtm-dbm">{signal} dBm</span>
              </div>
            </div>
          </div>
        )}

        {/* Battery */}
        {batteryPercent !== null && (
          <div className="rtm-item rtm-battery">
            <div className="rtm-icon">
              <Zap size={14} />
            </div>
            <div className="rtm-content">
              <div className="rtm-label">Battery</div>
              <div className="rtm-value">
                <div className="rtm-battery-bar">
                  <div
                    className="rtm-battery-fill"
                    style={{
                      width: `${batteryPercent}%`,
                      background:
                        batteryPercent <= 20 ? '#ef4444' :
                        batteryPercent <= 50 ? '#f59e0b' :
                        '#22c55e',
                    }}
                  />
                </div>
                <span>{Math.round(batteryPercent)}%</span>
              </div>
            </div>
          </div>
        )}

        {/* Speed */}
        {speed && (
          <div className="rtm-item rtm-speed">
            <div className="rtm-icon">
              <Gauge size={14} />
            </div>
            <div className="rtm-content">
              <div className="rtm-label">Speed</div>
              <div className="rtm-value">{Number(speed).toFixed(1)} km/h</div>
            </div>
          </div>
        )}

        {/* Last Update */}
        {timestamp && (
          <div className="rtm-item rtm-timestamp">
            <div className="rtm-icon">
              <Clock size={14} />
            </div>
            <div className="rtm-content">
              <div className="rtm-label">Last Update</div>
              <div className="rtm-value">{formatTimeAgo(timestamp)}</div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function formatTimeAgo(timestamp: unknown): string {
  if (!timestamp) return 'N/A';
  const ts = new Date(String(timestamp)).getTime();
  const now = Date.now();
  const diffMs = now - ts;
  const diffSecs = Math.floor(diffMs / 1000);
  const diffMins = Math.floor(diffSecs / 60);
  const diffHours = Math.floor(diffMins / 60);

  if (diffSecs < 60) return `${diffSecs}s ago`;
  if (diffMins < 60) return `${diffMins}m ago`;
  if (diffHours < 24) return `${diffHours}h ago`;
  return new Date(String(timestamp)).toLocaleString();
}
