
'use client';

import { useState, useEffect, useRef } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Navigation, MapPin, Activity } from 'lucide-react';

interface TrackingPoint {
  latitude: number;
  longitude: number;
  timestamp: string;
  isOnSite: boolean;
  distanceToSite: number | null;
  speed: number | null;
}

interface VehicleTrackingMapProps {
  contractId: string;
  siteLocation: { lat: number; lng: number };
  initialTracking?: TrackingPoint[];
}

export function VehicleTrackingMap({
  contractId,
  siteLocation,
  initialTracking = [],
}: VehicleTrackingMapProps) {
  const [tracking, setTracking] = useState<TrackingPoint[]>(initialTracking);
  const [isOnSite, setIsOnSite] = useState(false);
  const mapRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Poll for new tracking data every 30 seconds
    const interval = setInterval(fetchTracking, 30000);
    return () => clearInterval(interval);
  }, [contractId]);

  useEffect(() => {
    if (tracking.length > 0) {
      setIsOnSite(tracking[0].isOnSite);
      initializeMap();
    }
  }, [tracking]);

  const fetchTracking = async () => {
    try {
      const res = await fetch(`/api/tracking/vehicle?contractId=${contractId}&hours=24`);
      if (res.ok) {
        const data = await res.json();
        setTracking(data);
      }
    } catch (error) {
      console.error('Error fetching tracking:', error);
    }
  };

  const initializeMap = () => {
    if (!mapRef.current || typeof window === 'undefined') return;

    // Initialize Google Maps
    const google = (window as any).google;
    if (!google) return;

    const map = new google.maps.Map(mapRef.current, {
      zoom: 15,
      center: siteLocation,
    });

    // Add site marker
    new google.maps.Marker({
      position: siteLocation,
      map,
      title: 'Project Site',
      icon: {
        url: 'https://maps.google.com/mapfiles/ms/icons/red-dot.png',
      },
    });

    // Add tracking path
    if (tracking.length > 0) {
      const path = tracking.map((t) => ({
        lat: t.latitude,
        lng: t.longitude,
      }));

      new google.maps.Polyline({
        path,
        geodesic: true,
        strokeColor: '#3b82f6',
        strokeOpacity: 0.7,
        strokeWeight: 3,
        map,
      });

      // Add current location marker
      const currentLocation = path[0];
      new google.maps.Marker({
        position: currentLocation,
        map,
        title: 'Current Location',
        icon: {
          url: 'https://maps.google.com/mapfiles/ms/icons/blue-dot.png',
        },
      });

      // Center map on current location
      map.setCenter(currentLocation);
    }
  };

  const latestTracking = tracking[0];

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <div className="flex items-start justify-between">
            <div>
              <CardTitle>Live Vehicle Tracking</CardTitle>
              <CardDescription>
                Real-time location of your contractor
              </CardDescription>
            </div>
            <Badge variant={isOnSite ? 'success' : 'secondary'}>
              {isOnSite ? 'On Site' : 'En Route'}
            </Badge>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {latestTracking && (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
              <div className="flex items-center gap-3">
                <Navigation className="w-5 h-5 text-muted-foreground" />
                <div>
                  <p className="text-sm font-medium">Distance to Site</p>
                  <p className="text-sm text-muted-foreground">
                    {latestTracking.distanceToSite
                      ? `${(latestTracking.distanceToSite / 1000).toFixed(2)} km`
                      : 'On site'}
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <Activity className="w-5 h-5 text-muted-foreground" />
                <div>
                  <p className="text-sm font-medium">Last Updated</p>
                  <p className="text-sm text-muted-foreground">
                    {new Date(latestTracking.timestamp).toLocaleTimeString()}
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <MapPin className="w-5 h-5 text-muted-foreground" />
                <div>
                  <p className="text-sm font-medium">Status</p>
                  <p className="text-sm text-muted-foreground">
                    {latestTracking.isOnSite ? 'At project location' : 'Traveling'}
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Map Container */}
          <div
            ref={mapRef}
            className="w-full h-[400px] rounded-lg border bg-muted"
          />

          <p className="text-xs text-muted-foreground">
            Location updates every 30 seconds. This map shows the contractor's route and current position.
          </p>
        </CardContent>
      </Card>
    </div>
  );
}
