import { useQuery } from "@tanstack/react-query";
import { api } from "../api/ky";
import { Unit } from "../types/IUnit";
import GenericFloorPlan from "./floor-plans/GenericFloorPlan";
import { getFloorPlanConfigForUnit } from "../data/floor-plan-config";
import { ComplexName } from "../types/ComplexName";
import { mergeHqLoungeVirtualUnits } from "../utils/hqLoungeVirtualUnits";

// ─── Helpers ─────────────────────────────────────────────

function getFloorParam(complexName: ComplexName, unit: Unit): string {
  if (
    complexName === "dubai-marina" &&
    (unit.floor === 39 || unit.floor === 40)
  )
    return "39";
  if (
    complexName === "dubai-marina" &&
    (unit.floor === 41 || unit.floor === 42)
  )
    return "41";
  if (complexName === "hq" && (unit.floor === 29 || unit.floor === 30))
    return "29";
  return unit.floor.toString();
}

// ─── Component ───────────────────────────────────────────

function OnFloorMask({ unit }: { unit: Unit }) {
  const complexName = unit.projectSlug;
  const config = complexName
    ? getFloorPlanConfigForUnit(complexName, unit)
    : null;
  const floorParam = complexName ? getFloorParam(complexName, unit) : "";

  const { data: unitsOnFloor } = useQuery({
    enabled:
      !(
        complexName === "hq" && [19, 20, 23, 24, 27, 28].includes(unit.floor)
      ) && !config,
    queryKey: ["units-on-floor", complexName, floorParam, unit.wing],
    queryFn: () =>
      api
        .get(
          `units/on-floor?project=${complexName}&floor=${floorParam}${
            complexName === "marasi-drive" && unit.wing
              ? `&wing=${unit.wing}`
              : ""
          }`
        )
        .json<Unit[]>(),
  });

  if (!complexName || !config) return null;

  const baseUnits = unitsOnFloor ?? [unit];
  const units =
    complexName === "hq"
      ? mergeHqLoungeVirtualUnits(
          baseUnits,
          unit.floor,
          config.masks,
          config.getMaskKey
        )
      : baseUnits;

  // Marasi Drive uses component-based rendering (inline SVG)
  if (config.component) {
    const Component = config.component;
    return (
      <Component
        selectedFloor={unit.floor.toString()}
        unitsOnFloor={units}
        chosenUnit={unit}
        isUnitPage
      />
    );
  }

  // Dubai Marina & HQ use image-based rendering
  return (
    <GenericFloorPlan
      complexName={complexName}
      viewBox={config.viewBox}
      imagePath={config.imagePath}
      masks={config.masks}
      getMaskKey={config.getMaskKey}
      filterUnits={config.filterUnits}
      selectedFloor={unit.floor.toString()}
      unitsOnFloor={units}
      chosenUnit={unit}
      isUnitPage
      wing={config.wing}
    />
  );
}

export default OnFloorMask;
