'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';

import WarehouseForm from '@/components/pages/master-data/warehouse/form/WarehouseForm';

import { WarehouseApi } from '@/services/api/master-data';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';

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

  const warehouseId = searchParams.get('warehouseId');

  const { data: warehouse, isLoading: isLoadingWarehouse } = useSWR(
    warehouseId,
    (id: number) => WarehouseApi.getSingle(id)
  );

  if (!warehouseId) {
    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 (!isLoadingWarehouse && (!warehouse || isResponseError(warehouse))) {
    router.replace('/404');
    return;
  }

  return (
    <div className='w-full p-4 flex flex-row justify-center'>
      {isLoadingWarehouse && (
        <span className='loading loading-spinner loading-xl' />
      )}
      {!isLoadingWarehouse && isResponseSuccess(warehouse) && (
        <WarehouseForm type='edit' initialValues={warehouse.data} />
      )}
    </div>
  );
};

export default WarehouseEdit;
