'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 { isResponseSuccess } from '@/lib/api-helper';

const WarehouseDetail = () => {
  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) {
    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='detail' initialValues={warehouse.data} />
      )}
    </div>
  );
};

export default WarehouseDetail;
