'use client';

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

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

import { ClosingApi } from '@/services/api/closing';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
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))
  );

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

export default ClosingDetailPage;
