import { useState } from 'react';
import { Box, Text } from 'ink';
import { Select, Spinner } from '@inkjs/ui';
import type { McpPrompt, McpSession } from '../mcp-session.js';

interface PromptListViewProps {
  prompts: McpPrompt[];
  session: McpSession;
  onResult: (prompt: McpPrompt, content: unknown) => void;
  onError: (msg: string) => void;
  onBack: () => void;
}

export function PromptListView({ prompts, session, onResult, onError }: PromptListViewProps) {
  const [loading, setLoading] = useState<string | null>(null);

  if (prompts.length === 0) {
    return <Text dimColor>No prompts available.</Text>;
  }

  const options = prompts.map((p) => ({
    label: `${p.name}${p.description ? ` — ${p.description.slice(0, 60)}` : ''}`,
    value: p.name,
  }));

  if (loading) {
    return (
      <Box gap={1}>
        <Spinner label={`Getting prompt ${loading}...`} />
      </Box>
    );
  }

  return (
    <Box flexDirection="column">
      <Text bold>Prompts ({prompts.length}):</Text>
      <Box marginTop={1}>
        <Select
          options={options}
          onChange={async (name) => {
            const prompt = prompts.find((p) => p.name === name);
            if (!prompt) return;
            setLoading(name);
            try {
              const result = await session.getPrompt(name);
              onResult(prompt, result);
            } catch (err) {
              onError(`prompts/get failed: ${err instanceof Error ? err.message : String(err)}`);
            } finally {
              setLoading(null);
            }
          }}
        />
      </Box>
    </Box>
  );
}
