'use client';

/**
 * 발주 상세/수정 페이지 (Client Component)
 * V2 패턴: ?mode=edit로 수정 모드 전환
 */

import { use, useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { OrderDetailForm } from '@/components/business/construction/order-management';
import { getOrderDetailFull } from '@/components/business/construction/order-management/actions';
import { ServerErrorPage } from '@/components/common/ServerErrorPage';
import { GenericPageSkeleton } from '@/components/ui/skeleton';

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

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

  useEffect(() => {
    getOrderDetailFull(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 || !data) {
    return (
      <ServerErrorPage
        title="발주 정보를 불러올 수 없습니다"
        message={error || '발주 정보를 찾을 수 없습니다.'}
        showBackButton={true}
        showHomeButton={true}
      />
    );
  }

  return <OrderDetailForm mode={mode} orderId={id} initialData={data} />;
}
