import { useState, useCallback } from 'react';
import { TerminalEntry } from '../types/terminal';

export interface Workspace {
  id: string;
  name: string;
  history: TerminalEntry[];
  chatSessionId?: string;
  createdAt: Date;
  portfolioName?: string | null;
}

export const useTabs = () => {
  const [workspaces, setWorkspaces] = useState<Workspace[]>([
    {
      id: '1',
      name: 'Terminal 1',
      history: [
        {
          id: 'welcome',
          type: 'system',
          content: 'MosaicIQ Financial Terminal v1.0\nUse /portfolio to open portfolio tools.\nSlash commands (/) clear the panel. Natural language builds a conversation.',
          timestamp: new Date()
        }
      ],
      chatSessionId: undefined,
      createdAt: new Date()
    }
  ]);
  const [activeWorkspaceId, setActiveWorkspaceId] = useState('1');

  const activeWorkspace = workspaces.find(w => w.id === activeWorkspaceId) || workspaces[0];

  const createWorkspace = useCallback(() => {
    const newWorkspace: Workspace = {
      id: Date.now().toString(),
      name: `Terminal ${workspaces.length + 1}`,
      history: [
        {
          id: `welcome-${Date.now()}`,
          type: 'system',
          content: 'MosaicIQ Financial Terminal v1.0\nUse /portfolio to open portfolio tools.\nSlash commands (/) clear the panel. Natural language builds a conversation.',
          timestamp: new Date()
        }
      ],
      chatSessionId: undefined,
      createdAt: new Date()
    };

    setWorkspaces(prev => [...prev, newWorkspace]);
    setActiveWorkspaceId(newWorkspace.id);
    return newWorkspace.id;
  }, [workspaces.length]);

  const closeWorkspace = useCallback((id: string) => {
    // Don't allow closing the last workspace
    if (workspaces.length === 1) return;

    setWorkspaces(prev => {
      const filtered = prev.filter(w => w.id !== id);

      // If we closed the active workspace, switch to another
      if (id === activeWorkspaceId) {
        const newActive = filtered[0];
        setActiveWorkspaceId(newActive.id);
      }

      return filtered;
    });
  }, [workspaces, activeWorkspaceId]);

  const setActiveWorkspace = useCallback((id: string) => {
    setActiveWorkspaceId(id);
  }, []);

  const updateWorkspaceHistory = useCallback((id: string, history: TerminalEntry[]) => {
    setWorkspaces(prev =>
      prev.map(w =>
        w.id === id ? { ...w, history } : w
      )
    );
  }, []);

  const appendWorkspaceEntry = useCallback((id: string, entry: TerminalEntry) => {
    // Appending in place keeps a stable entry id available for later stream updates.
    setWorkspaces((prev) =>
      prev.map((workspace) =>
        workspace.id === id
          ? { ...workspace, history: [...workspace.history, entry] }
          : workspace,
      ),
    );
  }, []);

  const updateWorkspaceEntry = useCallback(
    (
      id: string,
      entryId: string,
      updater: (entry: TerminalEntry) => TerminalEntry,
    ) => {
      // Update a single entry without rebuilding unrelated workspaces.
      setWorkspaces((prev) =>
        prev.map((workspace) =>
          workspace.id === id
            ? {
                ...workspace,
                history: workspace.history.map((entry) =>
                  entry.id === entryId ? updater(entry) : entry,
                ),
              }
            : workspace,
        ),
      );
    },
    [],
  );

  const clearWorkspace = useCallback((id: string) => {
    setWorkspaces((prev) =>
      prev.map((workspace) =>
        workspace.id === id ? { ...workspace, history: [] } : workspace,
      ),
    );
  }, []);

  const setWorkspaceSession = useCallback((id: string, chatSessionId?: string) => {
    // Session ids are scoped per workspace so each tab can maintain an independent conversation.
    setWorkspaces((prev) =>
      prev.map((workspace) =>
        workspace.id === id ? { ...workspace, chatSessionId } : workspace,
      ),
    );
  }, []);

  const renameWorkspace = useCallback((id: string, name: string) => {
    setWorkspaces(prev =>
      prev.map(w =>
        w.id === id ? { ...w, name } : w
      )
    );
  }, []);

  const setPortfolioName = useCallback((id: string, portfolioName: string | null) => {
    setWorkspaces(prev =>
      prev.map(w =>
        w.id === id ? { ...w, portfolioName } : w
      )
    );
  }, []);

  return {
    workspaces,
    activeWorkspace,
    activeWorkspaceId,
    createWorkspace,
    closeWorkspace,
    setActiveWorkspace,
    updateWorkspaceHistory,
    appendWorkspaceEntry,
    updateWorkspaceEntry,
    clearWorkspace,
    setWorkspaceSession,
    renameWorkspace,
    setPortfolioName,
  };
};
