import type { MapMarker } from '@/components/map/MapView';
import { AREA_LABELS, resolveWorkerCoordinates, resolveWorkerPinArea } from '@/lib/geocode';
import {
  getListedWorkerSkills,
  getWorkerSkillLabel,
} from '@/components/workers/WorkerProfileDisplay';

export function buildWorkerMapMarkers(
  workers: Record<string, unknown>[],
  categorySlug?: string,
  regionSlug?: string
): MapMarker[] {
  const markers: MapMarker[] = [];

  for (const worker of workers) {
    const areas = worker.serviceAreas as { area: string }[] | undefined;
    const coords = resolveWorkerCoordinates(
      {
        id: worker.id as string,
        serviceAreas: areas,
      },
      regionSlug
    );
    const wUser = worker.user as {
      firstName: string;
      lastName: string;
      avatarUrl?: string | null;
    };
    const skills = worker.skills as { category: { name: string; slug: string } }[] | undefined;
    const otherSkills = worker.otherSkills as string | null | undefined;
    const isStudent = worker.isStudent === true;
    const matchedSkill = categorySlug
      ? skills?.find((s) => s.category.slug === categorySlug)
      : getListedWorkerSkills(skills)[0];
    const portfolioImages = worker.portfolioImages as
      | { id: string; url: string; title?: string | null }[]
      | undefined;
    const workerCounts = worker._count as { portfolioImages?: number } | undefined;

    const pinAreaKey = resolveWorkerPinArea(areas, regionSlug);
    const pinLabel = AREA_LABELS[pinAreaKey] || pinAreaKey;
    const allLabels = areas?.map((a) => AREA_LABELS[a.area] || a.area) ?? [];
    const otherLabels = allLabels.filter((label) => label !== pinLabel);

    markers.push({
      id: worker.id as string,
      type: 'worker',
      lat: coords.lat,
      lng: coords.lng,
      title: `${wUser.firstName} ${wUser.lastName}`,
      subtitle:
        (worker.headline as string) ||
        getWorkerSkillLabel(skills, otherSkills) ||
        (isStudent ? 'Student worker' : undefined),
      category: matchedSkill?.category.name ?? getWorkerSkillLabel(skills, otherSkills),
      location: pinLabel,
      serviceAreas:
        otherLabels.length > 0 ? `Also serves: ${otherLabels.join(', ')}` : undefined,
      rating: worker.averageRating as number | undefined,
      href: `/workers/${worker.id}`,
      portfolioImages,
      portfolioCount: workerCounts?.portfolioImages ?? portfolioImages?.length ?? 0,
      avatarUrl: wUser.avatarUrl,
      firstName: wUser.firstName,
      lastName: wUser.lastName,
    });
  }

  return markers;
}
