'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';
import { FlockApi } from '@/services/api/master-data';
import { ProjectFlockApi } from '@/services/api/production/project-flock';
import { ProjectFlockKandangApi } from '@/services/api/production';

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

  const closingId = searchParams.get('closingId');
  const kandangId = searchParams.get('kandangId'); // project flock kandang ID

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

  // WORKAROUND - get flock data from closing ID
  const { data: projectData, isLoading: isLoadingProject } = useSWR(
    `flock-${closingId}`,
    () => ProjectFlockApi.getSingle(Number(closingId))
  );
  // WORKAROUND - get kandang data from closing ID
  const { data: kandangData, isLoading: isLoadingKandang } = useSWR(
    kandangId ? `kandang-${closingId}-${kandangId}` : null,
    () => ProjectFlockKandangApi.getSingle(Number(kandangId))
  );

  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 ||
    isLoadingSales ||
    isLoadingHppEkspedisi ||
    isLoadingProject ||
    isLoadingKandang;

  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
          }
          projectData={
            isResponseSuccess(projectData) ? projectData.data : undefined
          }
          kandangData={
            isResponseSuccess(kandangData) ? kandangData.data : undefined
          }
        />
      )}
    </div>
  );
};

export default ClosingDetailPage;
