import { useState } from 'react';
import { api } from './api';

export const LAST_SESSION_KEY = 'madarx:last-chat-session-id:v1';

export function saveLastSessionId(id) {
  if (typeof window === 'undefined') return;
  try {
    if (id) window.localStorage.setItem(LAST_SESSION_KEY, id);
    else window.localStorage.removeItem(LAST_SESSION_KEY);
  } catch { /* storage is best-effort */ }
}

export function getSavedLastSessionId() {
  if (typeof window === 'undefined') return null;
  try { return window.localStorage.getItem(LAST_SESSION_KEY); }
  catch { return null; }
}

export function chatStateFromSession(session) {
  const msgs = (session?.messages || []).filter(m => (m.role === 'user' || m.role === 'assistant') && m.content);
  const next = msgs.map(m => ({ role: m.role === 'assistant' ? 'agent' : 'user', text: m.content }));
  if (!next.length) {
    next.push({ role: 'agent', text: 'Fresh workspace ready. I am the madarX Main Agent. Tell me what to create first.' });
  }
  return next;
}

export function useDashboardSessions({ sessionId, setSessionId, setChat, setUsage, setSelectedModel, setSessionArtifactId }) {
  const [sessions, setSessions] = useState([]);
  const [sessionsOpen, setSessionsOpen] = useState(false);

  async function refreshSessions() {
    try {
      const d = await api('/api/chat/sessions');
      setSessions(d.sessions || []);
    } catch { /* ignore — chat history is best-effort */ }
  }

  async function openSession(id) {
    setSessionsOpen(false);
    if (id === sessionId) return;
    setSessionArtifactId(null);
    try {
      const d = await api(`/api/chat/sessions/${encodeURIComponent(id)}`);
      const s = d.session;
      setSessionId(s.id);
      saveLastSessionId(s.id);
      setChat(chatStateFromSession(s));
      setUsage(u => ({
        ...u,
        model: s.model || u.model,
        input: s.total_input_tokens || 0,
        output: s.total_output_tokens || 0,
        cache_read: s.total_cache_read_tokens || 0,
        cache_creation: s.total_cache_creation_tokens || 0,
        context: s.last_context_tokens || 0,
      }));
      if (s.model) setSelectedModel(s.model);
    } catch { /* ignore */ }
  }

  function newSession() {
    setSessionsOpen(false);
    setSessionId(null);
    saveLastSessionId(null);
    setSessionArtifactId(null);
    setChat([{ role: 'agent', text: 'Fresh workspace ready. I am the madarX Main Agent. Tell me what to create first.' }]);
    setUsage(u => ({ ...u, input: 0, output: 0, cache_read: 0, cache_creation: 0, context: 0 }));
  }

  async function deleteSession(id) {
    try { await fetch(`/api/chat/sessions/${encodeURIComponent(id)}`, { method: 'DELETE' }); } catch {}
    if (id === sessionId) newSession();
    else {
      try { if (getSavedLastSessionId() === id) saveLastSessionId(null); } catch {}
    }
    await refreshSessions();
  }

  return {
    sessions,
    setSessions,
    sessionsOpen,
    setSessionsOpen,
    refreshSessions,
    openSession,
    newSession,
    deleteSession,
  };
}
