'use client';

import { useSuspenseQuery } from '@tanstack/react-query';
import { notFound } from 'next/navigation';
import { trainingRecordByIdOptions } from '../api/queries';
import type { TrainingRecord } from '../api/types';
import TrainingRecordForm from './training-record-form';

type TrainingRecordViewPageProps = {
  trainingRecordId: string;
  currentUser: {
    id: string;
    name: string;
    employeeId: number | null;
  };
  businessRole: 'IT' | 'HRD' | 'EMPLOYEE' | null;
  systemRole?: string | null;
};

export default function TrainingRecordViewPage({
  trainingRecordId,
  currentUser,
  businessRole,
  systemRole
}: TrainingRecordViewPageProps) {
  if (trainingRecordId === 'new') {
    return (
      <TrainingRecordForm
        initialData={null}
        pageTitle='สร้างประวัติการอบรม'
        currentUser={currentUser}
        businessRole={businessRole}
        systemRole={systemRole}
      />
    );
  }

  return (
    <EditTrainingRecordView
      trainingRecordId={Number(trainingRecordId)}
      currentUser={currentUser}
      businessRole={businessRole}
      systemRole={systemRole}
    />
  );
}

function EditTrainingRecordView({
  trainingRecordId,
  currentUser,
  businessRole,
  systemRole
}: {
  trainingRecordId: number;
  currentUser: {
    id: string;
    name: string;
    employeeId: number | null;
  };
  businessRole: 'IT' | 'HRD' | 'EMPLOYEE' | null;
  systemRole?: string | null;
}) {
  const { data } = useSuspenseQuery(trainingRecordByIdOptions(trainingRecordId));

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

  return (
    <TrainingRecordForm
      initialData={data.training_record as TrainingRecord}
      pageTitle='แก้ไขประวัติการอบรม'
      currentUser={currentUser}
      businessRole={businessRole}
      systemRole={systemRole}
    />
  );
}
