'use client';

import MarketingForm from '@/components/pages/marketing/form/MarketingForm';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { MarketingApi } from '@/services/api/marketing/marketing';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';

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

  const soId = searchParams.get('marketingId');

  const {
    data: marketing,
    isLoading: isLoading,
    mutate: refreshMarketing,
  } = useSWR(`get-so-${soId}`, () =>
    MarketingApi.getSingle(soId ? parseInt(soId) : 0)
  );

  if (!soId) {
    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 (!isLoading && (!marketing || isResponseError(marketing))) {
    router.replace('/404');
    return;
  }
  return (
    <div className='w-full p-4'>
      {isLoading && <span className='loading loading-spinner loading-xl' />}
      {!isLoading && isResponseSuccess(marketing) && (
        <MarketingForm
          formType='edit'
          initialValues={marketing.data}
          afterSubmit={() => {
            refreshMarketing();
          }}
        />
      )}
    </div>
  );
};
export default EditSalesOrder;
