"use client";

import { useRouter, useSearchParams } from "next/navigation";
import CO2GalvoList from "@/components/lists/CO2GalvoList";
import CO2GalvoDetail from "@/components/details/CO2GalvoDetail";

export default function CO2GalvoPanel() {
  const sp = useSearchParams();
  const router = useRouter();

  const id = sp.get("id");
  const view = sp.get("view") === "detail" && id ? "detail" : "list";

  function setView(next: "list" | "detail", nextId?: string | number) {
    const q = new URLSearchParams(sp.toString());
    q.set("t", "co2-galvo");
    if (next === "detail" && nextId != null) {
      q.set("view", "detail");
      q.set("id", String(nextId));
    } else {
      q.set("view", "list");
      q.delete("id");
      q.delete("edit");
    }
    router.replace(`/portal/laser-settings?${q.toString()}`, { scroll: false });
  }

  const linkFor = (sid: string | number, opts?: { edit?: boolean }) => {
    const q = new URLSearchParams(sp.toString());
    q.set("t", "co2-galvo");
    q.set("view", "detail");
    q.set("id", String(sid));
    if (opts?.edit) q.set("edit", "1"); else q.delete("edit");
    return `/portal/laser-settings?${q.toString()}`;
  };

  return (
    <div className="space-y-3">
    {/* App-style header (no big boxes) */}
    <div className="flex items-center gap-2">
    <button
    onClick={() => setView("list")}
    className={`px-3 py-1.5 rounded border ${view === "list" ? "bg-primary text-primary-foreground" : "hover:bg-muted"}`}
    >
    List
    </button>
    <button
    onClick={() => id && setView("detail", id)}
    disabled={!id}
    className={`px-3 py-1.5 rounded border ${view === "detail" ? "bg-primary text-primary-foreground" : "hover:bg-muted"} disabled:opacity-50`}
    >
    Detail
    </button>
    <div className="ml-auto text-sm text-muted-foreground">
    CO₂ Galvo Settings
    </div>
    </div>

    {/* Body */}
    {view === "list" ? (
      <div className="w-full">
      <CO2GalvoList linkFor={linkFor} />
      </div>
    ) : (
      <div className="w-full">
      {id ? (
        <>
        <CO2GalvoDetail id={id} editable />
        <div className="mt-2">
        <button
        className="px-2 py-1 border rounded text-sm"
        onClick={() => setView("list")}
        >
        Back
        </button>
        </div>
        </>
      ) : (
        <div className="text-sm text-muted-foreground">No record selected.</div>
      )}
      </div>
    )}
    </div>
  );
}
