import { useMemo } from 'react';
import { useGetClinic, useGetClinicHistory } from '@/shared/api/generated/clinics/clinics';
import { AnalysisStatus } from '@/shared/api/model/analysisStatus';
import type {
  WorkspaceData,
  WorkspaceRun,
  WorkspaceRunStatus,
} from '../types/workspace';

/**
 * /clinics/:clinicId 워크스페이스용 데이터 통합 훅.
 *
 * - useGetClinic: 클리닉 기본 정보 (hospital_name, hospital_name_en 등)
 * - useGetClinicHistory: 분석 run 목록 + 시계열 지표
 *
 * 백엔드에 plans 엔드포인트가 아직 없어 plans 는 빈 배열로 둠.
 * (필요해지면 useGetPlan / 별도 list 엔드포인트 추가 시 합쳐 채워넣기)
 */
export function useClinicWorkspace(clinicId: string | undefined) {
  const clinicQuery = useGetClinic(clinicId ?? '', {
    query: { enabled: !!clinicId },
  });
  const historyQuery = useGetClinicHistory(clinicId ?? '', {
    query: { enabled: !!clinicId },
  });

  const data = useMemo<WorkspaceData | null>(() => {
    if (!clinicId) return null;
    if (clinicQuery.data?.status !== 200) return null;
    if (historyQuery.data?.status !== 200) return null;

    const clinic = clinicQuery.data.data;
    const history = historyQuery.data.data;

    const runs: WorkspaceRun[] = history.runs.map((r) => ({
      runId: r.run_id,
      startedAt: r.started_at,
      completedAt: r.completed_at ?? null,
      status: normalizeRunStatus(r.status),
      overallScore: typeof r.overall_score === 'number' ? r.overall_score : null,
      // 백엔드에 분석 대상 targets 가 아직 없음 — 빈 배열
      targets: [],
    }));

    return {
      clinic: {
        clinicId: clinic.hospital_id,
        name: clinic.hospital_name,
        nameEn: clinic.hospital_name_en ?? undefined,
        location: clinic.road_address ?? undefined,
        defaultTargets: [],
      },
      runs,
      plans: [],
    };
  }, [clinicId, clinicQuery.data, historyQuery.data]);

  return {
    data,
    isLoading: clinicQuery.isLoading || historyQuery.isLoading,
    error:
      clinicQuery.error?.message ||
      historyQuery.error?.message ||
      (clinicQuery.data && clinicQuery.data.status !== 200 ? '클리닉 정보를 불러올 수 없습니다.' : null) ||
      (historyQuery.data && historyQuery.data.status !== 200 ? '분석 이력을 불러올 수 없습니다.' : null),
  };
}

function normalizeRunStatus(s: string): WorkspaceRunStatus {
  if (s === AnalysisStatus.completed) return 'completed';
  if (s === AnalysisStatus.failed) return 'failed';
  if (s === 'queued') return 'queued';
  return 'running';
}
