'use client';

import { use, useEffect, useState, useCallback } from 'react';
import { useSearchParams } from 'next/navigation';
import { EstimateDetailForm } from '@/components/business/construction/estimates';
import type { EstimateDetail } from '@/components/business/construction/estimates';
import { getEstimateDetail } from '@/components/business/construction/estimates/actions';
import { ServerErrorPage } from '@/components/common/ServerErrorPage';
import { GenericPageSkeleton } from '@/components/ui/skeleton';

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

export default function EstimateDetailPage({ params }: EstimateDetailPageProps) {
  const { id } = use(params);
  const searchParams = useSearchParams();

  // V2 패턴: mode 체크
  const mode = searchParams.get('mode') || 'view';
  const isEditMode = mode === 'edit';

  const [data, setData] = useState<EstimateDetail | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchData = useCallback(async () => {
    try {
      setIsLoading(true);
      setError(null);
      const result = await getEstimateDetail(id);
      if (result.success && result.data) {
        setData(result.data);
      } else {
        setError(result.error || '견적 정보를 불러오는데 실패했습니다.');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, [id]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  if (isLoading) return <GenericPageSkeleton />;

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

  return (
    <EstimateDetailForm
      mode={isEditMode ? 'edit' : 'view'}
      estimateId={id}
      initialData={data || undefined}
    />
  );
}