'use client';

import SupplierForm from '@/components/pages/master-data/supplier/form/SupplierForm';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { SupplierApi } from '@/services/api/master-data';
import { useSearchParams, useRouter } from 'next/navigation';
import useSWR from 'swr';

const SupplierDetail = () => {
  const router = useRouter();
  const searchParams = useSearchParams();

  // Get Query Params
  const supplierId = searchParams.get('supplierId');

  // Fetch Data
  const { data: supplier, isLoading: isLoadingSupplier } = useSWR(
    supplierId,
    (id: number) => SupplierApi.getSingle(id)
  );

  if (!supplierId) {
    router.back();

    return (
      <div className='w-full flex flex-row justify-center items-center p-4'>
        <span className='loading loading-spinner loading-xl' />
      </div>
    );
  }

  if (!isLoadingSupplier && (!supplier || isResponseError(supplier))) {
    router.replace('/404');
    return;
  }

  return (
    <div className='w-full p-4 flex flex-row justify-center'>
      {isLoadingSupplier && (
        <span className='loading loading-spinner loading-xl' />
      )}
      {!isLoadingSupplier && isResponseSuccess(supplier) && (
        <SupplierForm formType='detail' initialValues={supplier.data} />
      )}
    </div>
  );
};

export default SupplierDetail;