"use client";

import type { ReactNode } from "react";
import { APIProvider, Map, APILoadingStatus, ColorScheme, useApiLoadingStatus, type MapMouseEvent } from "@vis.gl/react-google-maps";
import { useTheme } from "next-themes";

export type GoogleMapConfig = { apiKey: string; mapId: string };
export const defaultMapCenter = { lat: -6.2, lng: 106.8167 };

function LoadingStatus() {
  const status = useApiLoadingStatus();
  if (status === APILoadingStatus.LOADED) return null;
  const failed = status === APILoadingStatus.FAILED || status === APILoadingStatus.AUTH_FAILURE;
  return (
    <div className="absolute inset-0 z-10 flex items-center justify-center bg-card/95 p-6 text-center">
      <p role={failed ? "alert" : "status"} className={failed ? "text-destructive" : "text-muted-foreground"}>
        {failed ? "Google Maps could not load. Check the Maps configuration or use the list and coordinate fields." : "Loading Google Maps…"}
      </p>
    </div>
  );
}

export function GoogleMapFrame({ config, children, center = defaultMapCenter, onClick, className = "h-[520px]" }: {
  config: GoogleMapConfig;
  children?: ReactNode;
  center?: { lat: number; lng: number };
  onClick?: (event: MapMouseEvent) => void;
  className?: string;
}) {
  const { resolvedTheme } = useTheme();
  if (!config.apiKey || !config.mapId) return (
    <div role="status" className={`flex items-center justify-center rounded-lg border bg-muted p-6 text-center text-muted-foreground ${className}`}>
      Google Maps is not configured. The list and coordinate fields remain available.
    </div>
  );
  return (
    <APIProvider apiKey={config.apiKey} region="ID" language="en" solutionChannel="">
      <div className={`relative overflow-hidden rounded-lg bg-muted ${className}`}>
        <Map
          mapId={config.mapId}
          defaultCenter={center}
          defaultZoom={14}
          colorScheme={resolvedTheme === "dark" ? ColorScheme.DARK : ColorScheme.LIGHT}
          gestureHandling="cooperative"
          mapTypeControl={false}
          streetViewControl={false}
          onClick={onClick}
          style={{ width: "100%", height: "100%" }}
        >{children}</Map>
        <LoadingStatus />
      </div>
    </APIProvider>
  );
}
