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

interface SettingsScreenProps {
  onBack: () => void;
}

interface MenuItem {
  label: string;
  value: string;
}

type SettingsState = 'menu' | 'edit_api_key' | 'success' | 'error';

const menuItems: MenuItem[] = [
  { label: 'Configure API Key', value: 'configure' },
  { label: 'Test API Key', value: 'test' },
  { label: 'Back to Main Menu', value: 'back' },
];

export const SettingsScreen: React.FC<SettingsScreenProps> = ({ onBack }) => {
  const [state, setState] = useState<SettingsState>('menu');
  const [apiKey, setApiKeyInput] = useState('');
  const [currentApiKey, setCurrentApiKey] = useState('');
  const [errorMessage, setErrorMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [successContext, setSuccessContext] = useState<'saved' | 'tested'>('saved');

  useEffect(() => {
    // Load current API key on component mount
    const key = getOpenAIKey();
    setCurrentApiKey(key);
  }, []);

  useInput((input, key) => {
    if (key.escape) {
      if (state === 'menu') {
        onBack();
      } else {
        setState('menu');
        setApiKeyInput('');
        setErrorMessage('');
      }
    }
  });

  const handleMenuSelect = (item: MenuItem) => {
    switch (item.value) {
      case 'configure':
        setState('edit_api_key');
        setApiKeyInput(currentApiKey);
        break;
      case 'test':
        testApiKey();
        break;
      case 'back':
        onBack();
        break;
    }
  };

  const testApiKey = async () => {
    setIsLoading(true);
    setErrorMessage('');
    
    try {
      // Test if we can create an OpenAI client with the current key
      const OpenAI = (await import('openai')).default;
      const client = new OpenAI({
        apiKey: currentApiKey || undefined,
      });
      
      // Make a simple API call to test the key
      await client.chat.completions.create({
        model: 'gpt-3.5-turbo',
        messages: [{ role: 'user', content: 'Hello' }],
        max_tokens: 1,
      });
      
      setSuccessContext('tested');
      setState('success');
    } catch (error) {
      setErrorMessage(`API key test failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
      setState('error');
    } finally {
      setIsLoading(false);
    }
  };

  const handleSaveApiKey = () => {
    if (!apiKey.trim()) {
      setErrorMessage('Please enter an API key');
      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) {
      setCurrentApiKey(apiKey.trim());
      setSuccessContext('saved');
      setState('success');
      setErrorMessage('');
    } else {
      setErrorMessage('Failed to save API key to .env file');
      setState('error');
    }
    
    setIsLoading(false);
  };

  const maskApiKey = (key: string) => {
    if (!key || key.length < 10) return key;
    return key.slice(0, 7) + '...' + key.slice(-4);
  };

  if (state === 'edit_api_key') {
    return (
      <Box flexDirection="column" padding={2}>
        <Box marginBottom={2}>
          <Text bold color="blue">
            Configure OpenAI API Key
          </Text>
        </Box>
        
        <Box flexDirection="column" marginBottom={2}>
          <Box marginBottom={1}>
            <Text color="cyan">
              Enter your OpenAI API key:
            </Text>
          </Box>
          
          <Box marginBottom={1}>
            <Text color="gray">
              You can get your API key from: https://platform.openai.com/api-keys
            </Text>
          </Box>
          
          <Box width={60}>
            <TextInput
              value={apiKey}
              onChange={setApiKeyInput}
              placeholder="sk-..."
              mask="*"
              onSubmit={handleSaveApiKey}
            />
          </Box>
          
          {errorMessage && (
            <Box marginTop={1}>
              <Text color="red">
                {errorMessage}
              </Text>
            </Box>
          )}
        </Box>
        
        <Box flexDirection="row" gap={2}>
          <Text color="gray">
            [Enter] Save
          </Text>
          <Text color="gray">
            [Esc] Cancel
          </Text>
        </Box>
        
        {isLoading && (
          <Box marginTop={1}>
            <Text color="yellow">
              Saving...
            </Text>
          </Box>
        )}
      </Box>
    );
  }

  if (state === 'success') {
    return (
      <Box flexDirection="column" padding={2}>
        <Box marginBottom={2}>
          <Text bold color="green">
            Success!
          </Text>
        </Box>
        
        <Box marginBottom={2}>
          <Text color="gray">
            {successContext === 'saved' ? 'API key has been saved successfully!' : 'API key is working correctly!'}
          </Text>
        </Box>
        
        <Box flexDirection="row" gap={2}>
          <Text color="gray">
            [Esc] Back to Settings
          </Text>
        </Box>
      </Box>
    );
  }

  if (state === 'error') {
    return (
      <Box flexDirection="column" padding={2}>
        <Box marginBottom={2}>
          <Text bold color="red">
            Error
          </Text>
        </Box>
        
        <Box marginBottom={2}>
          <Text color="red">
            {errorMessage}
          </Text>
        </Box>
        
        <Box flexDirection="row" gap={2}>
          <Text color="gray">
            [Esc] Back to Settings
          </Text>
        </Box>
      </Box>
    );
  }

  // Main settings menu
  return (
    <Box flexDirection="column" padding={2}>
      <Box marginBottom={2}>
        <Text bold color="blue">
          Settings
        </Text>
      </Box>
      
      <Box flexDirection="column" marginBottom={2}>
        <Box marginBottom={1}>
          <Text color="cyan">
            OpenAI API Configuration
          </Text>
        </Box>
        
        <Box marginBottom={1}>
          <Text color="gray">
            Current API Key: {currentApiKey ? maskApiKey(currentApiKey) : 'Not configured'}
          </Text>
        </Box>
        
        <Box marginBottom={1}>
          <Text color="gray">
            Status: {hasOpenAIKey() ? 
              <Text color="green">Configured</Text> : 
              <Text color="red">Not configured</Text>
            }
          </Text>
        </Box>
      </Box>
      
      <Box flexDirection="column" alignItems="center" marginBottom={2}>
        <Box marginBottom={2}>
          <Text color="gray">
            Use arrow keys to navigate, Enter to select:
          </Text>
        </Box>
        
        <Box width={30}>
          <SelectInput items={menuItems} onSelect={handleMenuSelect} />
        </Box>
      </Box>
      
      <Box flexDirection="column">
        {!hasOpenAIKey() && (
          <Box marginBottom={1}>
            <Text color="yellow">
              Note: AI features require an OpenAI API key
            </Text>
          </Box>
        )}
        
        {isLoading && (
          <Box marginBottom={1}>
            <Text color="yellow">
              Testing API key...
            </Text>
          </Box>
        )}
        
        <Box marginBottom={1}>
          <Text color="gray">
            Press [Esc] to go back to main menu
          </Text>
        </Box>
      </Box>
    </Box>
  );
}; 