'use client';

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

import BankForm from '@/components/pages/master-data/bank/form/BankForm';

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

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

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

  const { data: bank, isLoading: isLoadingBank } = useSWR(
    bankId,
    (id: number) => BankApi.getSingle(id)
  );

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

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

export default BankDetail;
