'use client';

import { use, useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { HandoverReportDetailForm, getHandoverReportDetail } from '@/components/business/construction/handover-report';
import { ServerErrorPage } from '@/components/common/ServerErrorPage';
import { GenericPageSkeleton } from '@/components/ui/skeleton';

interface HandoverReportDetailPageProps {
  params: Promise<{
    id: string;
    locale: string;
  }>;
}

export default function HandoverReportDetailPage({ params }: HandoverReportDetailPageProps) {
  const { id } = use(params);
  const _router = useRouter();
  const searchParams = useSearchParams();
  const mode = searchParams.get('mode') === 'edit' ? 'edit' : 'view';
  const [data, setData] = useState<Awaited<ReturnType<typeof getHandoverReportDetail>>['data']>(undefined);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    getHandoverReportDetail(id)
      .then(result => {
        if (result.data) {
          setData(result.data);
        } else {
          setError('인수인계서 정보를 찾을 수 없습니다.');
        }
      })
      .catch(() => {
        setError('인수인계서 정보를 불러오는 중 오류가 발생했습니다.');
      })
      .finally(() => setIsLoading(false));
  }, [id]);

  if (isLoading) return <GenericPageSkeleton />;

  if (error) {
    return (
      <ServerErrorPage
        title="인수인계서 정보를 불러올 수 없습니다"
        message={error}
        showBackButton={true}
        showHomeButton={true}
      />
    );
  }

  return (
    <HandoverReportDetailForm
      mode={mode}
      reportId={id}
      initialData={data}
    />
  );
}
