import React, { useState } from 'react';
import { Box, Text, useInput } from 'ink';
import TextInput from 'ink-text-input';
import { setOpenAIKey } from '../utils.js';

interface ApiKeyPromptProps {
  onComplete: (hasApiKey: boolean) => void;
}

export const ApiKeyPrompt: React.FC<ApiKeyPromptProps> = ({ onComplete }) => {
  const [apiKey, setApiKey] = useState('');
  const [errorMessage, setErrorMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  useInput((input, key) => {
    if (key.escape) {
      // Continue without API key
      onComplete(false);
    }
  });

  const handleSubmit = () => {
    if (!apiKey.trim()) {
      setErrorMessage('Please enter an API key or press Esc to continue without AI features');
      return;
    }

    // Validate API key format (should start with sk-)
    if (!apiKey.startsWith('sk-')) {
      setErrorMessage('OpenAI API keys should start with "sk-"');
      return;
    }

    setIsLoading(true);
    const success = setOpenAIKey(apiKey.trim());
    
    if (success) {
      onComplete(true);
    } else {
      setErrorMessage('Failed to save API key to .env file');
      setIsLoading(false);
    }
  };

  const handleSkip = () => {
    onComplete(false);
  };

  return (
    <Box flexDirection="column" padding={2}>
      <Box marginBottom={2}>
        <Text bold color="blue">
          Welcome to BookGrabs!
        </Text>
      </Box>
      
      <Box flexDirection="column" marginBottom={2}>
        <Box marginBottom={1}>
          <Text color="cyan">
            OpenAI API Key Setup
          </Text>
        </Box>
        
        <Box marginBottom={1}>
          <Text color="gray">
            BookGrabs uses OpenAI's GPT to intelligently select the best search results
          </Text>
        </Box>
        
        <Box marginBottom={1}>
          <Text color="gray">
            and standardize book titles and authors for better organization.
          </Text>
        </Box>
        
        <Box marginBottom={2}>
          <Text color="yellow">
            To use these AI features, please enter your OpenAI API key:
          </Text>
        </Box>
        
        <Box marginBottom={1}>
          <Text color="gray">
            Get your API key from: https://platform.openai.com/api-keys
          </Text>
        </Box>
        
        <Box width={60}>
          <TextInput
            value={apiKey}
            onChange={setApiKey}
            placeholder="sk-... (or press Esc to skip)"
            mask="*"
            onSubmit={handleSubmit}
          />
        </Box>
        
        {errorMessage && (
          <Box marginTop={1}>
            <Text color="red">
              {errorMessage}
            </Text>
          </Box>
        )}
      </Box>
      
      <Box flexDirection="column" marginBottom={2}>
        <Box marginBottom={1}>
          <Text color="cyan">
            Options:
          </Text>
        </Box>
        
        <Box flexDirection="column" paddingLeft={2}>
          <Box marginBottom={1}>
            <Text color="gray">
              [Enter] Save API key and continue
            </Text>
          </Box>
          
          <Box marginBottom={1}>
            <Text color="gray">
              [Esc] Skip and continue without AI features
            </Text>
          </Box>
        </Box>
      </Box>
      
      <Box flexDirection="column">
        <Box marginBottom={1}>
          <Text color="gray">
            Note: You can configure your API key later in Settings if you skip this step.
          </Text>
        </Box>
        
        <Box marginBottom={1}>
          <Text color="yellow">
            Without an API key, BookGrabs will use basic search result selection.
          </Text>
        </Box>
        
        {isLoading && (
          <Box marginBottom={1}>
            <Text color="yellow">
              Saving API key...
            </Text>
          </Box>
        )}
      </Box>
    </Box>
  );
}; 