import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect, forwardRef, useRef, useImperativeHandle } from "react";
import { Text } from "ink";
import { logger } from "@dexto/core";
import { BaseSelector } from "../base/BaseSelector.js";
const SessionSelector = forwardRef(
  function SessionSelector2({ isVisible, onSelectSession, onClose, agent, currentSessionId }, ref) {
    const baseSelectorRef = useRef(null);
    useImperativeHandle(
      ref,
      () => ({
        handleInput: (input, key) => {
          return baseSelectorRef.current?.handleInput(input, key) ?? false;
        }
      }),
      []
    );
    const [sessions, setSessions] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [selectedIndex, setSelectedIndex] = useState(0);
    useEffect(() => {
      if (!isVisible) return;
      let cancelled = false;
      setIsLoading(true);
      const fetchSessions = async () => {
        try {
          const sessionIds = await agent.listSessions();
          const sessionList = await Promise.all(
            sessionIds.map(async (id) => {
              try {
                const metadata = await agent.getSessionMetadata(id);
                return {
                  id,
                  metadata,
                  isCurrent: id === currentSessionId
                };
              } catch {
                return {
                  id,
                  metadata: void 0,
                  isCurrent: id === currentSessionId
                };
              }
            })
          );
          sessionList.sort((a, b) => {
            if (a.isCurrent) return -1;
            if (b.isCurrent) return 1;
            const aTime = a.metadata?.lastActivity || 0;
            const bTime = b.metadata?.lastActivity || 0;
            return bTime - aTime;
          });
          if (!cancelled) {
            setSessions(sessionList);
            setIsLoading(false);
            setSelectedIndex(0);
          }
        } catch (error) {
          if (!cancelled) {
            logger.error(
              `Failed to fetch sessions: ${error instanceof Error ? error.message : "Unknown error"}`,
              { error }
            );
            setSessions([]);
            setIsLoading(false);
          }
        }
      };
      void fetchSessions();
      return () => {
        cancelled = true;
      };
    }, [isVisible, agent, currentSessionId]);
    const formatSession = (session) => {
      const parts = [];
      if (session.metadata?.title) {
        parts.push(session.metadata.title);
      } else {
        parts.push("New Session");
      }
      if (session.metadata?.parentSessionId) {
        parts.push(`forked from ${session.metadata.parentSessionId.slice(0, 8)}`);
      }
      parts.push(session.id.slice(0, 8));
      if (session.metadata?.lastActivity) {
        const now = Date.now();
        const diff = now - session.metadata.lastActivity;
        const minutes = Math.floor(diff / 6e4);
        const hours = Math.floor(minutes / 60);
        const days = Math.floor(hours / 24);
        if (days > 0) {
          parts.push(`${days}d ago`);
        } else if (hours > 0) {
          parts.push(`${hours}h ago`);
        } else if (minutes > 0) {
          parts.push(`${minutes}m ago`);
        } else {
          parts.push("just now");
        }
      }
      return parts.join(" \u2022 ");
    };
    const formatItem = (session, isSelected) => /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(Text, { color: isSelected ? "cyan" : "gray", bold: isSelected, children: formatSession(session) }),
      session.isCurrent && /* @__PURE__ */ jsxs(Text, { color: isSelected ? "cyan" : "gray", bold: isSelected, children: [
        " ",
        "\u2190 Current"
      ] })
    ] });
    const handleSelect = (session) => {
      onSelectSession(session.id);
    };
    return /* @__PURE__ */ jsx(
      BaseSelector,
      {
        ref: baseSelectorRef,
        items: sessions,
        isVisible,
        isLoading,
        selectedIndex,
        onSelectIndex: setSelectedIndex,
        onSelect: handleSelect,
        onClose,
        formatItem,
        title: "Select Session",
        borderColor: "cyan",
        loadingMessage: "Loading sessions...",
        emptyMessage: "No sessions found"
      }
    );
  }
);
var SessionSelectorRefactored_default = SessionSelector;
export {
  SessionSelectorRefactored_default as default
};
