'use client';

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

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

  const costumerId = searchParams.get('customerId');

  const { data: costumer, isLoading: isLoadingCostumer } = useSWR(
    costumerId,
    (id: number) => CustomerApi.getSingle(id)
  );

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

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

export default CustomerDetail;
