'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';

import ClosingDetail from '@/components/pages/closing/ClosingDetail';

import { ClosingApi } from '@/services/api/closing';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';

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

  const closingId = searchParams.get('closingId');

  const { data: closing, isLoading: isLoadingClosing } = useSWR(
    closingId,
    (id: number) => ClosingApi.getGeneralInfo(id)
  );

  const { data: salesData, isLoading: isLoadingSales } = useSWR(
    closingId ? `sales-${closingId}` : null,
    () => ClosingApi.getPenjualan(Number(closingId))
  );

  const { data: hppEkspedisiData, isLoading: isLoadingHppEkspedisi } = useSWR(
    closingId ? `hpp-ekspedisi-${closingId}` : null,
    () => ClosingApi.getHppEkspedisi(Number(closingId))
  );

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

  const isLoading = isLoadingClosing || isLoadingHppEkspedisi;
  // const isLoading = isLoadingClosing || isLoadingSales || isLoadingHppEkspedisi;

  return (
    <div className='w-full p-4 flex flex-row justify-center'>
      {isLoading && <span className='loading loading-spinner loading-xl' />}

      {!isLoading && isResponseSuccess(closing) && (
        <ClosingDetail
          id={Number(closingId)}
          initialValue={closing.data}
          salesData={isResponseSuccess(salesData) ? salesData.data : undefined}
          hppExpeditionData={
            isResponseSuccess(hppEkspedisiData)
              ? hppEkspedisiData.data
              : undefined
          }
        />
      )}
    </div>
  );
};

export default ClosingDetailPage;
