import { useEffect, useState } from 'react';
import type { Agent, BranchInfo, ChatMessage, ModelOverrides } from '../../../api';
import { AgentAPI, ChatAPI } from '../../../api';
import { parseAgentModels } from '../utils/agentModels';

export function useChatData(args: {
  agentId?: string;
  sessionId: string | null;
  highlightId: string | null;
  setHighlightId: (v: string | null) => void;
  scrollBottom: (force?: boolean) => void;
  initialScrollDoneRef: { current: boolean };
  setOverrides: (updater: (prev: ModelOverrides) => ModelOverrides) => void;
  abort: () => void;
}) {
  const { agentId, sessionId, highlightId, setHighlightId, scrollBottom, initialScrollDoneRef, setOverrides, abort } = args;
  const [agent, setAgent] = useState<Agent | null>(null);
  const [agentList, setAgentList] = useState<Agent[]>([]);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [branches, setBranches] = useState<Record<string, BranchInfo>>({});

  const loadAgent = async () => {
    if (!agentId) {
      setAgent(null);
      setMessages([]);
      return;
    }
    const a = await AgentAPI.detail(agentId);
    setAgent(a);
    const models = parseAgentModels(a.model);
    const firstModel = models[0];
    if (firstModel) {
      setOverrides((o) => ({
        ...o,
        model: o.model || firstModel.name,
        model_id: o.model_id || firstModel.id
      }));
    }
  };

  const loadAgentList = async () => {
    try {
      const list = await AgentAPI.list();
      setAgentList(list);
    } catch {
      // ignore
    }
  };

  const loadMessages = async () => {
    if (!agentId) return;
    const his = await ChatAPI.history(agentId, sessionId || undefined);
    setMessages(Array.isArray(his.messages) ? his.messages : []);
    setBranches(his.branches || {});
    requestAnimationFrame(() => {
      if (highlightId) {
        const el = document.getElementById('msg-' + highlightId);
        if (el) {
          el.scrollIntoView({ behavior: 'smooth', block: 'center' });
          setTimeout(() => setHighlightId(null), 3000);
          return;
        }
      }
      if (!initialScrollDoneRef.current) {
        scrollBottom(true);
        initialScrollDoneRef.current = true;
      } else {
        scrollBottom();
      }
    });
  };

  useEffect(() => {
    loadAgentList();
  }, []);

  useEffect(() => {
    if (!agentId) {
      setAgent(null);
      setMessages([]);
      setOverrides(() => ({}));
      return abort;
    }
    loadAgent();
    setOverrides(() => ({}));
    return abort;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [agentId]);

  useEffect(() => {
    initialScrollDoneRef.current = false;
  }, [agentId]);

  useEffect(() => {
    if (!agentId) return;
    loadMessages();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sessionId, highlightId, agentId]);

  return {
    agent,
    agentList,
    messages,
    setMessages,
    branches,
    setBranches,
    loadMessages
  };
}

