import { useMemo } from 'react';
import { GeoJSON, Tooltip } from 'react-leaflet';
import type { Cut, PublicCut } from '@/types/api';

interface Props {
  cuts: (Cut | PublicCut)[];
  visibleCutIds: Set<string>;
}

function CutLayer({ cut }: { cut: Cut | PublicCut }) {
  const geojsonData = useMemo(() => {
    try {
      return JSON.parse(cut.geojson) as GeoJSON.GeoJsonObject;
    } catch {
      return null;
    }
  }, [cut.geojson]);

  const opacity = parseFloat(String(cut.opacity));

  if (!geojsonData) return null;

  return (
    <GeoJSON
      key={cut.id}
      data={geojsonData}
      style={{
        color: cut.color,
        fillColor: cut.color,
        fillOpacity: isNaN(opacity) ? 0.3 : opacity,
        weight: 2,
        opacity: 0.8,
      }}
    >
      <Tooltip sticky>{cut.name}</Tooltip>
    </GeoJSON>
  );
}

export default function CutOverlays({ cuts, visibleCutIds }: Props) {
  const visibleCuts = useMemo(
    () => cuts.filter((c) => visibleCutIds.has(c.id)),
    [cuts, visibleCutIds]
  );

  return (
    <>
      {visibleCuts.map((cut) => (
        <CutLayer key={cut.id} cut={cut} />
      ))}
    </>
  );
}
