"use client";

import { useState } from "react";
import { SegmentedControl } from "@/components/ui/SegmentedControl";
import type { OpenPositionResolved } from "@/lib/positions";
import { AsOfPicker } from "./AsOfPicker";
import { EmployeeTree } from "./EmployeeTree";
import { PositionTree } from "./PositionTree";
import { ReorgWorkbench } from "./ReorgWorkbench";
import type { OrgDepartment, OrgDivision, OrgEmployee, OrgTeam, ReorgScenarioSummary } from "./types";

type View = "ma" | "pos" | "reo";

type OrgChartClientProps = {
  employees: OrgEmployee[];
  divisions: OrgDivision[];
  departments: OrgDepartment[];
  teams: OrgTeam[];
  openPositions: OpenPositionResolved[];
  reorgScenarios: ReorgScenarioSummary[];
  asOf: string;
  today: string;
  projectedCount: number;
  historyStartsAt: string | null;
  /** Arrived via "Im Organigramm anzeigen" — unfold and centre this person. */
  focusId: string | null;
};

export function OrgChartClient({
  employees,
  divisions,
  departments,
  teams,
  openPositions,
  reorgScenarios,
  asOf,
  today,
  projectedCount,
  historyStartsAt,
  focusId,
}: OrgChartClientProps) {
  const [view, setView] = useState<View>("ma");
  const isToday = asOf === today;

  return (
    <div className="flex flex-col gap-4">
      <SegmentedControl<View>
        value={view}
        onChange={setView}
        options={[
          { value: "ma", label: "Mitarbeiter" },
          { value: "pos", label: "Positionen" },
          { value: "reo", label: "Reorganisation" },
        ]}
      />

      {view !== "reo" && (
        <AsOfPicker asOf={asOf} today={today} projectedCount={projectedCount} historyStartsAt={historyStartsAt} />
      )}

      {view === "ma" && <EmployeeTree employees={employees} focusId={focusId} />}
      {view === "pos" && (
        <PositionTree employees={employees} divisions={divisions} departments={departments} teams={teams} openPositions={openPositions} />
      )}
      {view === "reo" &&
        (isToday ? (
          <ReorgWorkbench employees={employees} divisions={divisions} departments={departments} teams={teams} reorgScenarios={reorgScenarios} />
        ) : (
          // A reorg planned against a past or projected roster would be
          // applied to the *live* org anyway — better to send the user back
          // to today than to let them assemble moves from a roster that is
          // not the one the change would hit.
          <div className="rounded border border-border bg-white p-6 text-sm text-ink-body">
            <p className="font-semibold text-ink">Reorganisation nur zum heutigen Stand</p>
            <p className="mt-1 text-ink-muted">
              Es ist ein abweichender Stichtag gewählt. Reorganisationen wirken immer auf die aktuelle Struktur — wechseln
              Sie zurück auf „Heute“, um eine zu planen.
            </p>
          </div>
        ))}
    </div>
  );
}
