'use client';

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

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

  const { data: marketing, isLoading: isLoading } = 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) && (
        <SalesOrderDetail initialValues={marketing.data} />
      )}
    </div>
  );
};

export default DetailSalesOrder;
