"use client";

import { useState, useRef, useCallback } from "react";
import dynamic from "next/dynamic";
import { useSession } from "next-auth/react";
import { LayerPanel, getDefaultVisibility } from "./layer-panel";
import { BasemapSwitcher } from "./basemap-switcher";
import { SearchBar } from "./search-bar";
import { SelectionToolbar, type SelectionMode } from "./selection-toolbar";
import { FeatureInfoPanel } from "./feature-info-panel";
import { SetupBanner } from "./setup-banner";
import type { MapViewerHandle } from "./map-viewer";
import type {
  BasemapId, ClickedFeature, LayerVisibility, SearchResult, SelectedFeature,
} from "../types";
import { GeoportalV2 } from "../v2/geoportal-v2";

const MapViewer = dynamic(
  () => import("./map-viewer").then((m) => ({ default: m.MapViewer })),
  {
    ssr: false,
    loading: () => (
      <div className="flex items-center justify-center h-full bg-muted/30">
        <p className="text-sm text-muted-foreground">Se incarca harta...</p>
      </div>
    ),
  }
);

export function GeoportalModule() {
  // Faza C cutover — branch on session.useGisAc (server-decided per request,
  // exposed via NextAuth session callback in src/core/auth/auth-options.ts).
  // Flag flip = Infisical USE_GIS_AC=1 + container force-recreate.
  const { data: session } = useSession();
  const useGisAc = Boolean((session as { useGisAc?: boolean } | null)?.useGisAc);
  if (useGisAc) {
    return <GeoportalV2 />;
  }
  return <GeoportalV1Legacy />;
}

function GeoportalV1Legacy() {
  const mapHandleRef = useRef<MapViewerHandle>(null);
  const [basemap, setBasemap] = useState<BasemapId>("liberty");
  const [layerVisibility, setLayerVisibility] = useState<LayerVisibility>(getDefaultVisibility);
  const [clickedFeature, setClickedFeature] = useState<ClickedFeature | null>(null);
  const [selectionMode, setSelectionMode] = useState<SelectionMode>("off");
  const [selectedFeatures, setSelectedFeatures] = useState<SelectedFeature[]>([]);
  const handleFeatureClick = useCallback((feature: ClickedFeature | null) => {
    // null = clicked on empty space, close panel
    if (!feature || !feature.properties) {
      setClickedFeature(null);
      return;
    }
    setClickedFeature(feature);
  }, []);

  const handleSearchResult = useCallback((result: SearchResult) => {
    if (result.coordinates) {
      mapHandleRef.current?.flyTo(result.coordinates, result.type === "uat" ? 12 : 17);
    }
  }, []);

  const handleSelectionModeChange = useCallback((mode: SelectionMode) => {
    if (mode === "off") {
      mapHandleRef.current?.clearSelection();
      setSelectedFeatures([]);
    }
    setSelectionMode(mode);
  }, []);

  return (
    <div className="absolute inset-0">
      <MapViewer
        ref={mapHandleRef}
        className="h-full w-full"
        basemap={basemap}
        selectionType={selectionMode}
        onFeatureClick={handleFeatureClick}
        onSelectionChange={setSelectedFeatures}
        layerVisibility={layerVisibility}
      />

      {/* Setup banner (auto-hides when ready) */}
      <div className="absolute top-3 left-1/2 -translate-x-1/2 z-20 w-auto max-w-lg">
        <SetupBanner />
      </div>

      {/* Top-left: search + layers */}
      <div className="absolute top-3 left-3 z-10 flex flex-col gap-2 max-w-xs">
        <SearchBar onResultSelect={handleSearchResult} />
        <LayerPanel visibility={layerVisibility} onVisibilityChange={setLayerVisibility} />
      </div>

      {/* Top-right: basemap switcher + feature panel (aligned) */}
      <div className="absolute top-3 right-14 z-10 flex flex-col items-end gap-2">
        <BasemapSwitcher value={basemap} onChange={setBasemap} />
        {clickedFeature && selectionMode === "off" && (
          <FeatureInfoPanel feature={clickedFeature} onClose={() => setClickedFeature(null)} />
        )}
      </div>

      {/* Bottom-left: selection toolbar */}
      <div className="absolute bottom-8 left-3 z-10">
        <SelectionToolbar
          selectedFeatures={selectedFeatures}
          selectionMode={selectionMode}
          onSelectionModeChange={handleSelectionModeChange}
          onClearSelection={() => { mapHandleRef.current?.clearSelection(); setSelectedFeatures([]); }}
        />
      </div>
    </div>
  );
}
