'use client';

import { useSuspenseQuery } from '@tanstack/react-query';
import { notFound } from 'next/navigation';
import type { Employee } from '../api/types';
import { employeeByIdOptions } from '../api/queries';
import EmployeeForm from './employee-form';

type EmployeeViewPageProps = {
  employeeId: string;
};

export default function EmployeeViewPage({ employeeId }: EmployeeViewPageProps) {
  if (employeeId === 'new') {
    return <EmployeeForm initialData={null} pageTitle='สร้างพนักงาน' organizationName='-' />;
  }

  return <EditEmployeeView employeeId={Number(employeeId)} />;
}

function EditEmployeeView({ employeeId }: { employeeId: number }) {
  const { data } = useSuspenseQuery(employeeByIdOptions(employeeId));

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

  return (
    <EmployeeForm
      initialData={data.employee as Employee}
      pageTitle='แก้ไขข้อมูลพนักงาน'
      organizationName={data.employee.company ?? '-'}
    />
  );
}
