'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 toast from 'react-hot-toast';
import useSWR from 'swr';

const EditMarketingDelivery = () => {
  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='add_deliver'
          initialValues={marketing.data}
          afterSubmit={() => {
            refreshMarketing();
          }}
        />
      )}
    </div>
  );
};
export default EditMarketingDelivery;
