'use client';

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

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

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: salesReport, isLoading: isLoadingSalesReport } = useSWR(
    closingId,
    (id: number) => ClosingApi.getPenjualan(id)
  );

  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;
  }

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

      {!isLoadingClosing && isResponseSuccess(closing) && (
        <ClosingDetail id={Number(closingId)} initialValue={closing.data} />
      )}
      {!isLoadingSalesReport && isResponseSuccess(salesReport) && (
        <SalesReportTable type='detail' initialValues={salesReport.data} />
      )}
    </div>
  );
};

export default ClosingDetailPage;
