import { useCallback, useEffect, useState } from 'react';
import { api } from '@/api/client';
import type { Session } from '@/api/types';
import { sessionEvents } from './sessionEvents';

export function useSessions(projectId: string | undefined) {
  const [sessions, setSessions] = useState<Session[] | null>(null);
  const [error, setError] = useState<string | null>(null);

  const refresh = useCallback(async () => {
    if (!projectId) {
      setSessions(null);
      return;
    }
    try {
      const list = await api.sessions.listForProject(projectId);
      setSessions(list);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'failed to load sessions');
    }
  }, [projectId]);

  useEffect(() => {
    void refresh();
  }, [refresh]);

  useEffect(() => {
    return sessionEvents.subscribe((event) => {
      if (event.type !== 'session_renamed') return;
      setSessions((prev) => {
        if (!prev) return prev;
        let changed = false;
        const next = prev.map((s) => {
          if (s.id !== event.session_id) return s;
          if (s.name === event.name) return s;
          changed = true;
          return { ...s, name: event.name };
        });
        return changed ? next : prev;
      });
    });
  }, []);

  const create = useCallback(
    async (body: { name?: string; model?: string; system_prompt?: string }) => {
      if (!projectId) throw new Error('no project');
      const created = await api.sessions.create(projectId, body);
      await refresh();
      return created;
    },
    [projectId, refresh]
  );

  const remove = useCallback(
    async (id: string) => {
      await api.sessions.remove(id);
      await refresh();
    },
    [refresh]
  );

  return { sessions, error, refresh, create, remove };
}
