'use client';

import { useMemo } from 'react';
import { MapPin } from 'lucide-react';
import { MapView } from '@/components/map/MapView';
import { buildJobMapMarkers } from '@/components/map/jobMarkers';
import { useAuth } from '@/contexts/AuthContext';
import { useRegion } from '@/contexts/RegionContext';
import { getWorkerPortalMapViewport } from '@/lib/region';
import { cn } from '@/lib/utils';

interface JobsMapPanelProps {
  jobs: Record<string, unknown>[];
  loading?: boolean;
  className?: string;
  jobHref?: (id: string) => string;
  emptyTitle?: string;
  emptySubtitle?: string;
}

export function JobsMapPanel({
  jobs,
  loading = false,
  className,
  jobHref = (id) => `/worker/jobs/${id}`,
  emptyTitle = 'No jobs to show on map',
  emptySubtitle = 'Jobs with a location will appear as pins. Try another filter or check back later.',
}: JobsMapPanelProps) {
  const { user } = useAuth();
  const { slug: contextSlug } = useRegion();
  const { center, zoom } = getWorkerPortalMapViewport(
    user?.workerProfile as { serviceAreas?: { area: string }[] } | undefined,
    contextSlug
  );

  const markers = useMemo(
    () => buildJobMapMarkers(jobs, jobHref),
    [jobs, jobHref]
  );

  return (
    <div
      className={cn(
        'relative overflow-hidden rounded-xl border border-border bg-slate-50 shadow-sm',
        className
      )}
    >
      <MapView
        markers={markers}
        defaultCenter={center}
        defaultZoom={zoom}
        focusOnRegion
        className="h-full w-full"
      />
      {loading && (
        <div className="absolute top-3 left-3 z-10 flex items-center gap-2 rounded-md bg-white/95 border border-border px-3 py-1.5 text-xs text-muted shadow-sm">
          <div className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
          Updating map…
        </div>
      )}
      {!loading && markers.length === 0 && (
        <div className="absolute inset-0 flex flex-col items-center justify-center bg-slate-50/90 text-center p-8 pointer-events-none">
          <MapPin className="h-10 w-10 text-muted mb-3" />
          <p className="font-medium text-slate-900">{emptyTitle}</p>
          <p className="text-sm text-muted mt-1 max-w-sm">{emptySubtitle}</p>
        </div>
      )}
      {!loading && markers.length > 0 && (
        <div className="absolute top-3 left-3 z-10 rounded-md bg-white/95 border border-border px-3 py-1.5 text-xs text-muted shadow-sm">
          <span className="inline-block h-2 w-2 rounded-full bg-accent mr-1.5 align-middle" />
          {markers.length} job{markers.length !== 1 ? 's' : ''} on map
        </div>
      )}
    </div>
  );
}
