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

interface ToolDetailViewProps {
  tool: McpTool;
  session: McpSession;
  onResult: (data: unknown) => void;
  onError: (msg: string) => void;
  onBack: () => void;
  onLoadingChange?: (loading: boolean) => void;
}

interface SchemaProperty {
  type?: string;
  description?: string;
}

export function ToolDetailView({ tool, session, onResult, onError, onLoadingChange }: ToolDetailViewProps) {
  const [loading, _setLoading] = useState(false);
  const setLoading = (v: boolean) => { _setLoading(v); onLoadingChange?.(v); };
  const [argsJson, setArgsJson] = useState('{}');

  // Extract properties from input schema
  const schema = tool.inputSchema as { properties?: Record<string, SchemaProperty>; required?: string[] } | undefined;
  const properties = schema?.properties ?? {};
  const required = new Set(schema?.required ?? []);
  const propNames = Object.keys(properties);

  const handleExecute = async () => {
    setLoading(true);
    try {
      let args: Record<string, unknown>;
      try {
        args = JSON.parse(argsJson) as Record<string, unknown>;
      } catch {
        onError('Invalid JSON for arguments');
        setLoading(false);
        return;
      }
      const result = await session.callTool(tool.name, args);
      onResult(result);
    } catch (err) {
      onError(`tools/call failed: ${err instanceof Error ? err.message : String(err)}`);
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <Box flexDirection="column">
      <Text bold color="cyan">{tool.name}</Text>
      {tool.description && <Text>{tool.description}</Text>}

      {propNames.length > 0 && (
        <Box flexDirection="column" marginTop={1}>
          <Text bold>Schema:</Text>
          {propNames.map((name) => {
            const prop = properties[name]!;
            const req = required.has(name) ? ' (required)' : '';
            return (
              <Text key={name} dimColor>
                  {name}: {prop.type ?? 'any'}{req}{prop.description ? ` — ${prop.description}` : ''}
              </Text>
            );
          })}
        </Box>
      )}

      <Box flexDirection="column" marginTop={1}>
        <Text bold>Arguments (JSON):</Text>
        <Box>
          <Text color="cyan">&gt; </Text>
          <TextInput
            placeholder="{}"
            defaultValue="{}"
            onChange={setArgsJson}
            onSubmit={handleExecute}
          />
        </Box>
        <Text dimColor>Press Enter to execute</Text>
      </Box>
    </Box>
  );
}
