'use client';

import MarketingDetail from '@/components/pages/marketing/detail/MarketingDetail';
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 DetailMarketing = () => {
  const router = useRouter();
  const searchParams = useSearchParams();

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

  const {
    data: marketing,
    isLoading: isLoading,
    mutate: refreshMarketing,
  } = useSWR(soId, (id: number) => MarketingApi.getSingle(id));

  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) && (
        <MarketingDetail
          initialValues={marketing.data}
          refresh={refreshMarketing}
        />
      )}
    </div>
  );
};

export default DetailMarketing;
