'use client';

import { use, useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import ContractDetailForm from '@/components/business/construction/contract/ContractDetailForm';
import { getContractDetail } from '@/components/business/construction/contract';
import { ServerErrorPage } from '@/components/common/ServerErrorPage';
import { GenericPageSkeleton } from '@/components/ui/skeleton';

interface ContractDetailPageProps {
  params: Promise<{ id: string }>;
}

export default function ContractDetailPage({ params }: ContractDetailPageProps) {
  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 getContractDetail>>['data']>(undefined);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    getContractDetail(id)
      .then(result => {
        if (result.success && 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 (
    <ContractDetailForm
      mode={mode}
      contractId={id}
      initialData={data}
    />
  );
}
