import { useEffect, useMemo, useState } from "react";
import { loadGalaxyData } from "../../r3f/shared/galaxyData";
import { getSystemPoiPosition } from "../../r3f/shared/poiOrbit";
import type { GalaxySystem, Vec3 } from "../../r3f/shared/types";
import { MOVEMENT_SYSTEM_SCALE, MovementScene } from "../../r3f/movement/MovementScene";
import type { LocalEntity, LocalWaypoint } from "../../r3f/movement/movementState";
import type { GameSliceSession } from "../types";
import { SLICE_BELT, SLICE_POI_NAMES, SLICE_STATION } from "../sliceWorld";
import { metricLabel, slicePanel } from "./sliceStyles";
import { SliceProgressBar } from "./SliceProgressBar";

const entities: LocalEntity[] = [
  { id: "slice-belt", name: SLICE_BELT.name, type: "asteroid", x: 620, y: 320, distance: 42 },
  { id: "slice-station", name: SLICE_STATION.name, type: "station", x: 430, y: 260, distance: 8 },
];

function fallbackPosition(poiId: string | null): Vec3 {
  if (poiId === SLICE_BELT.poiId) return [26, 0, -8];
  if (poiId === SLICE_STATION.poiId) return [-10, 0, 10];
  return [0, 0, 0];
}

function lerp(a: Vec3, b: Vec3, t: number): Vec3 {
  return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];
}

export function SliceTravelStage({ session, progress }: { session: GameSliceSession; progress: number }) {
  const [currentSystem, setCurrentSystem] = useState<GalaxySystem | null>(null);
  const operation = session.activeOperation?.kind === "travel" ? session.activeOperation : null;

  useEffect(() => {
    loadGalaxyData().then(({ systems }) => {
      setCurrentSystem(systems.find((system) => system.id === session.currentSystemId) ?? systems.find((system) => system.id === "sol") ?? null);
    });
  }, [session.currentSystemId]);

  const targetPoiId = operation?.targetPoiId ?? session.currentPoiId;
  const targetName = operation?.targetPoiName ?? SLICE_POI_NAMES[targetPoiId ?? ""] ?? "Local waypoint";
  const targetPosition = useMemo(() => {
    if (!currentSystem || !targetPoiId) return fallbackPosition(targetPoiId);
    return getSystemPoiPosition({
      systemId: currentSystem.id,
      planets: currentSystem.planets,
      pointsOfInterest: currentSystem.pointsOfInterest,
      poiId: targetPoiId,
      scale: MOVEMENT_SYSTEM_SCALE,
      expanded: true,
    });
  }, [currentSystem, targetPoiId]);
  const startPosition = fallbackPosition(session.currentPoiId);
  const shipPosition = operation ? lerp(startPosition, targetPosition, progress) : startPosition;
  const waypoints: LocalWaypoint[] = operation ? [{ id: targetPoiId ?? "target", name: targetName, type: "poi", systemId: operation.targetSystemId, poiId: targetPoiId ?? undefined, position: targetPosition }] : [];

  return (
    <section className="slice-loop-panel" style={{ ...slicePanel, position: "relative", height: "100%", minHeight: 0, overflow: "hidden" }}>
      <MovementScene
        currentSystemId={session.currentSystemId}
        currentSystem={currentSystem}
        localEntities={entities}
        localWaypoints={waypoints}
        shipPosition={shipPosition}
        onFrame={() => {}}
        onWaypointPick={() => {}}
        onPoiPick={() => {}}
      />
      <div style={{ position: "absolute", left: 14, right: 14, bottom: 14, zIndex: 1, padding: 12, border: "1px solid rgba(148,163,184,0.22)", borderRadius: 8, background: "rgba(8,12,20,0.84)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", gap: 12, marginBottom: 8 }}>
          <span style={metricLabel}>Local Travel</span>
          <span style={{ color: "#f0a030" }}>{targetName}</span>
        </div>
        <SliceProgressBar value={progress} />
      </div>
    </section>
  );
}
