'use client';

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

import MovementForm from '@/components/pages/inventory/movement/form/MovementForm';
import { MovementApi } from '@/services/api/inventory';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';

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

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

  const { data: movement, isLoading: isLoadingMovement } = useSWR(
    movementId,
    (id: number) => MovementApi.getSingle(id)
  );

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

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

export default MovementDetail;
