import { useEffect, useMemo, useState } from 'react';
import { fetchErrorLogs } from '../errorLogApi';
import { buildErrorReferenceSummary, buildErrorSourceSummary, getDefaultErrorResource } from './errorLogUtils';
import type { ChatPanelView } from './types';

type UseErrorLogsOptions = {
  activeView: ChatPanelView;
  hasAccess: boolean;
};

export function useErrorLogs({ activeView, hasAccess }: UseErrorLogsOptions) {
  const [errorLogs, setErrorLogs] = useState<Awaited<ReturnType<typeof fetchErrorLogs>>>([]);
  const [selectedErrorLogId, setSelectedErrorLogId] = useState<number | null>(null);
  const [isLoadingErrorLogs, setIsLoadingErrorLogs] = useState(false);
  const [errorLogLoadError, setErrorLogLoadError] = useState('');
  const [activeErrorResourceUrl, setActiveErrorResourceUrl] = useState('');
  const [isErrorDetailExpanded, setIsErrorDetailExpanded] = useState(false);

  const loadErrorLogs = async () => {
    if (!hasAccess || isLoadingErrorLogs) {
      return;
    }

    setIsLoadingErrorLogs(true);
    setErrorLogLoadError('');

    try {
      const items = await fetchErrorLogs(50);
      setErrorLogs(items);
      setSelectedErrorLogId((current) => current ?? items[0]?.id ?? null);
    } catch (error) {
      setErrorLogLoadError(error instanceof Error ? error.message : '에러 로그를 불러오지 못했습니다.');
    } finally {
      setIsLoadingErrorLogs(false);
    }
  };

  useEffect(() => {
    if (activeView !== 'errors' || !hasAccess) {
      return;
    }

    void loadErrorLogs();
  }, [activeView, hasAccess]);

  const selectedErrorLog = useMemo(
    () => errorLogs.find((item) => item.id === selectedErrorLogId) ?? errorLogs[0] ?? null,
    [errorLogs, selectedErrorLogId],
  );
  const selectedErrorLogReferenceSummary = useMemo(
    () => (selectedErrorLog ? buildErrorReferenceSummary(selectedErrorLog) : null),
    [selectedErrorLog],
  );
  const activeErrorResource = useMemo(
    () =>
      selectedErrorLogReferenceSummary?.resources.find((resource) => resource.url === activeErrorResourceUrl)
      ?? getDefaultErrorResource(selectedErrorLogReferenceSummary?.resources ?? []),
    [activeErrorResourceUrl, selectedErrorLogReferenceSummary],
  );
  const errorSourceSummary = useMemo(() => buildErrorSourceSummary(errorLogs), [errorLogs]);

  useEffect(() => {
    const nextUrl = getDefaultErrorResource(selectedErrorLogReferenceSummary?.resources ?? [])?.url ?? '';
    setActiveErrorResourceUrl(nextUrl);
  }, [selectedErrorLog?.id, selectedErrorLogReferenceSummary]);

  return {
    errorLogs,
    selectedErrorLog,
    selectedErrorLogId,
    selectedErrorLogReferenceSummary,
    activeErrorResource,
    errorSourceSummary,
    isLoadingErrorLogs,
    errorLogLoadError,
    activeErrorResourceUrl,
    isErrorDetailExpanded,
    setSelectedErrorLogId,
    setActiveErrorResourceUrl,
    setIsErrorDetailExpanded,
    loadErrorLogs,
  };
}
