'use client';

import UniformityDetail from '@/components/pages/production/uniformity/detail/UniformityDetail';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { UniformityApi } from '@/services/api/uniformity';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';

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

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

  const { data: uniformity, isLoading: isLoadingUniformity } = useSWR(
    uniformityId,
    (id: string) => UniformityApi.getUniformityDetail(parseInt(id))
  );

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

  return (
    <div className='w-full h-full flex flex-col justify-center'>
      {isLoadingUniformity && (
        <div className='w-full flex flex-row justify-center items-center p-4 min-h-screen'>
          <span className='loading loading-spinner loading-xl' />
        </div>
      )}
      {isResponseSuccess(uniformity) && (
        <UniformityDetail initialValues={uniformity.data} />
      )}
    </div>
  );
};

export default UniformityDetailPage;
