"use client";

import { useMemo, useState } from "react";
import {
  ComposableMap,
  Geographies,
  Geography,
  Sphere,
  Graticule,
} from "react-simple-maps";
import { countryNameFromIso2, iso2FromGeography } from "@/lib/iso-3166";
import type { CountryMapRow } from "./types";

const WORLD_TOPO_JSON = "https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json";

type Props = {
  countryRows: CountryMapRow[];
};

export default function WorldVisitMap({ countryRows }: Props) {
  const [tip, setTip] = useState<{ name: string; visits: number; x: number; y: number } | null>(
    null,
  );

  const countryVisitsByIso2 = useMemo(() => {
    return countryRows.reduce<Record<string, number>>((acc, row) => {
      const code = String(row.countryCode || "").toUpperCase();
      if (code.length === 2) acc[code] = row.visits || 0;
      return acc;
    }, {});
  }, [countryRows]);

  const maxCountryVisits = Math.max(1, ...countryRows.map((r) => r.visits || 0));

  return (
    <div className="relative overflow-hidden rounded-md border bg-slate-50">
      <ComposableMap projectionConfig={{ scale: 147 }} className="h-auto w-full">
        <Sphere stroke="#e2e8f0" strokeWidth={0.5} fill="#f8fafc" />
        <Graticule stroke="#e2e8f0" strokeWidth={0.35} />
        <Geographies geography={WORLD_TOPO_JSON}>
          {({ geographies }) =>
            geographies.map((geo) => {
              const iso2 = iso2FromGeography(geo);
              const visits = countryVisitsByIso2[iso2] || 0;
              const intensity = visits > 0 ? Math.min(0.9, visits / maxCountryVisits) : 0;
              const name =
                String((geo.properties as { name?: string } | undefined)?.name || "") ||
                countryNameFromIso2(iso2);
              return (
                <Geography
                  key={String(geo.rsmKey)}
                  geography={geo}
                  fill={visits > 0 ? `rgba(15, 118, 110, ${0.22 + intensity * 0.7})` : "#e2e8f0"}
                  stroke="#cbd5e1"
                  strokeWidth={0.4}
                  onMouseEnter={(event: { clientX: number; clientY: number }) => {
                    setTip({
                      name,
                      visits,
                      x: event.clientX,
                      y: event.clientY,
                    });
                  }}
                  onMouseMove={(event: { clientX: number; clientY: number }) => {
                    setTip((prev) =>
                      prev
                        ? { ...prev, x: event.clientX, y: event.clientY }
                        : { name, visits, x: event.clientX, y: event.clientY },
                    );
                  }}
                  onMouseLeave={() => setTip(null)}
                />
              );
            })
          }
        </Geographies>
      </ComposableMap>
      {tip ? (
        <div
          className="pointer-events-none fixed z-50 rounded-md border bg-white px-2.5 py-1.5 text-xs shadow-md"
          style={{ left: tip.x + 12, top: tip.y + 12 }}
        >
          <p className="font-medium text-slate-800">{tip.name}</p>
          <p className="text-slate-500">{tip.visits} visit{tip.visits === 1 ? "" : "s"}</p>
        </div>
      ) : null}
    </div>
  );
}
