'use client';

import { use, useEffect, useState, useCallback } from 'react';
import { useSearchParams } from 'next/navigation';
import { SiteBriefingForm, getSiteBriefing } from '@/components/business/construction/site-briefings';
import { ServerErrorPage } from '@/components/common/ServerErrorPage';

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

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

  const fetchData = useCallback(() => {
    setIsLoading(true);
    setError(null);
    getSiteBriefing(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 (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-muted-foreground">로딩 중...</div>
      </div>
    );
  }

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

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