'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { GoogleMap, Marker, useLoadScript } from '@react-google-maps/api';
import { MapPin } from 'lucide-react';
import { DAVAO_REGION_CENTER } from '@/lib/geocode';

export const GOOGLE_MAPS_SCRIPT_ID = 'ehandyhire-google-maps';

const JOB_ICON = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png';
const WORKER_ICON = 'http://maps.google.com/mapfiles/ms/icons/orange-dot.png';

export interface MapPinPoint {
  lat: number;
  lng: number;
  label?: string;
}

interface LocationMapProps {
  pins: MapPinPoint[];
  pinType?: 'job' | 'worker';
  className?: string;
}

const mapOptions: google.maps.MapOptions = {
  disableDefaultUI: true,
  zoomControl: true,
  streetViewControl: false,
  mapTypeControl: false,
  fullscreenControl: false,
  draggable: true,
  scrollwheel: false,
};

export function LocationMap({ pins, pinType = 'job', className }: LocationMapProps) {
  const apiKey = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY ?? '';
  const { isLoaded, loadError } = useLoadScript({
    googleMapsApiKey: apiKey,
    id: GOOGLE_MAPS_SCRIPT_ID,
    preventGoogleFontsLoading: true,
  });
  const [authFailure, setAuthFailure] = useState(false);

  useEffect(() => {
    const w = window as Window & { gm_authFailure?: () => void };
    const prev = w.gm_authFailure;
    w.gm_authFailure = () => setAuthFailure(true);
    return () => {
      w.gm_authFailure = prev;
    };
  }, []);

  const center = useMemo(() => {
    if (pins.length === 0) return DAVAO_REGION_CENTER;
    if (pins.length === 1) return { lat: pins[0].lat, lng: pins[0].lng };
    const lat = pins.reduce((s, p) => s + p.lat, 0) / pins.length;
    const lng = pins.reduce((s, p) => s + p.lng, 0) / pins.length;
    return { lat, lng };
  }, [pins]);

  const zoom = pins.length === 1 ? 14 : 11;

  const onLoad = useCallback(
    (map: google.maps.Map) => {
      if (pins.length <= 1) return;
      const bounds = new google.maps.LatLngBounds();
      pins.forEach((p) => bounds.extend({ lat: p.lat, lng: p.lng }));
      map.fitBounds(bounds, 40);
    },
    [pins]
  );

  if (!apiKey || loadError || authFailure) {
    return (
      <div className={`flex items-center justify-center rounded-lg border border-border bg-slate-50 text-sm text-muted ${className ?? 'h-48'}`}>
        Map unavailable
      </div>
    );
  }

  if (!isLoaded) {
    return (
      <div className={`flex items-center justify-center rounded-lg border border-border bg-slate-50 ${className ?? 'h-48'}`}>
        <div className="loading-spinner" />
      </div>
    );
  }

  const icon = pinType === 'job' ? JOB_ICON : WORKER_ICON;

  return (
    <div className={`relative z-0 isolate overflow-hidden rounded-lg border border-border ${className ?? 'h-48'}`}>
      <GoogleMap
        mapContainerStyle={{ width: '100%', height: '100%' }}
        center={center}
        zoom={zoom}
        options={mapOptions}
        onLoad={onLoad}
      >
        {pins.map((pin, i) => (
          <Marker
            key={`${pin.lat}-${pin.lng}-${i}`}
            position={{ lat: pin.lat, lng: pin.lng }}
            icon={icon}
            title={pin.label}
          />
        ))}
      </GoogleMap>
    </div>
  );
}

interface LocationSectionProps {
  heading?: string;
  showHeading?: boolean;
  address?: string;
  pins: MapPinPoint[];
  pinType?: 'job' | 'worker';
  note?: string;
}

export function LocationSection({
  heading = 'Location',
  showHeading = true,
  address,
  pins,
  pinType = 'job',
  note,
}: LocationSectionProps) {
  if (pins.length === 0 && !address) return null;

  return (
    <section>
      {showHeading && (
        <h2 className="font-bold text-slate-900 mb-2 flex items-center gap-2">
          <MapPin className="h-4 w-4 text-[var(--home-amber)]" />
          {heading}
        </h2>
      )}
      {address && (
        <p className="text-sm text-muted mb-3">{address}</p>
      )}
      {pins.length > 0 ? (
        <LocationMap pins={pins} pinType={pinType} className="h-52 sm:h-56" />
      ) : (
        <div className="rounded-lg border border-border bg-slate-50 p-4 text-sm text-muted">
          Location: {address}
        </div>
      )}
      {note && (
        <p className="text-xs text-muted mt-2">{note}</p>
      )}
    </section>
  );
}
