'use client';

import { use, useEffect, useState, useCallback } from 'react';
import { useSearchParams } from 'next/navigation';
import { ProgressBillingDetailForm } from '@/components/business/construction/progress-billing';
import { getProgressBillingDetail } from '@/components/business/construction/progress-billing/actions';
import { ServerErrorPage } from '@/components/common/ServerErrorPage';
import { GenericPageSkeleton } from '@/components/ui/skeleton';

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

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

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

  const [data, setData] = useState<Awaited<ReturnType<typeof getProgressBillingDetail>>['data']>(undefined);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchData = useCallback(() => {
    setIsLoading(true);
    setError(null);
    getProgressBillingDetail(id)
      .then(result => {
        if (result.success && result.data) {
          setData(result.data);
        } else {
          setError('기성청구 정보를 찾을 수 없습니다.');
        }
      })
      .catch(() => {
        setError('기성청구 정보를 불러오는 중 오류가 발생했습니다.');
      })
      .finally(() => setIsLoading(false));
  }, [id]);

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

  if (isLoading) return <GenericPageSkeleton />;

  if (error || !data) {
    return (
      <ServerErrorPage
        title="기성청구 정보를 불러올 수 없습니다"
        message={error || '기성청구 정보를 찾을 수 없습니다.'}
        onRetry={fetchData}
        showBackButton={true}
        showHomeButton={true}
      />
    );
  }

  return (
    <ProgressBillingDetailForm
      mode={isEditMode ? 'edit' : 'view'}
      billingId={id}
      initialData={data}
    />
  );
}
