'use client';

import { useEffect, useState, useCallback } from 'react';
import { useParams, useSearchParams } from 'next/navigation';
import IssueDetailForm from '@/components/business/construction/issue-management/IssueDetailForm';
import { getIssue } from '@/components/business/construction/issue-management/actions';
import type { Issue } from '@/components/business/construction/issue-management/types';
import { ServerErrorPage } from '@/components/common/ServerErrorPage';
import { GenericPageSkeleton } from '@/components/ui/skeleton';

export default function IssueDetailPage() {
  const params = useParams();
  const searchParams = useSearchParams();
  const id = params.id as string;

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

  const [issue, setIssue] = useState<Issue | undefined>(undefined);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchData = useCallback(async () => {
    try {
      setIsLoading(true);
      setError(null);
      const result = await getIssue(id);
      if (result.success && result.data) {
        setIssue(result.data);
      } else {
        setError(result.error || '이슈를 찾을 수 없습니다.');
      }
    } 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 <IssueDetailForm issue={issue} mode={isEditMode ? 'edit' : 'view'} />;
}