"use client";

import { useSuspenseQuery } from "@tanstack/react-query";
import type { TrainingMatrix } from "../api/types";
import { notFound } from "next/navigation";
import TrainingMatrixForm from "./training-matrix-form";
import { trainingMatrixByIdOptions } from "../api/queries";

type TrainingMatrixViewPageProps = {
  matrixId: string;
};

export default function TrainingMatrixViewPage({
  matrixId,
}: TrainingMatrixViewPageProps) {
  if (matrixId === "new") {
    return (
      <TrainingMatrixForm
        initialData={null}
        pageTitle="สร้างแผนการอบรมตามตำแหน่ง"
      />
    );
  }

  return <EditTrainingMatrixView matrixId={Number(matrixId)} />;
}

function EditTrainingMatrixView({ matrixId }: { matrixId: number }) {
  const { data } = useSuspenseQuery(trainingMatrixByIdOptions(matrixId));

  if (!data?.success || !data?.training_matrix) {
    notFound();
  }

  return (
    <TrainingMatrixForm
      initialData={data.training_matrix as TrainingMatrix}
      pageTitle="แก้ไขแผนการอบรมตามตำแหน่ง"
    />
  );
}
