'use client';

import { use, useEffect, useState, useCallback } from 'react';
import { useSearchParams } from 'next/navigation';
import PartnerForm from '@/components/business/construction/partners/PartnerForm';
import { getPartner } from '@/components/business/construction/partners/actions';
import { ServerErrorPage } from '@/components/common/ServerErrorPage';
import { GenericPageSkeleton } from '@/components/ui/skeleton';

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

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

  const fetchData = useCallback(() => {
    setIsLoading(true);
    setError(null);
    getPartner(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) {
    return (
      <ServerErrorPage
        title="협력업체 정보를 불러올 수 없습니다"
        message={error}
        onRetry={fetchData}
        showBackButton={true}
        showHomeButton={true}
      />
    );
  }

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