import React, { useState } from 'react';
import { Box, Text, useInput } from 'ink';
import TextInput from 'ink-text-input';
import { useAuth } from '../../state/auth-context.js';
import { useNavigation } from '../../state/navigation-context.js';
import { LoadingSpinner } from '../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../shared/ErrorDisplay.js';

type Field = 'username' | 'password';

export function LoginScreen() {
  const { login, loading, error, clearError } = useAuth();
  const { navigate } = useNavigation();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [activeField, setActiveField] = useState<Field>('username');

  useInput((input, key) => {
    if (loading) return;

    if (key.tab || key.downArrow) {
      setActiveField((f) => (f === 'username' ? 'password' : 'username'));
    }
    if (key.upArrow) {
      setActiveField((f) => (f === 'password' ? 'username' : 'password'));
    }
    if (key.escape && error) {
      clearError();
    }
    void input; // suppress unused warning
  });

  const handleUsernameSubmit = (value: string) => {
    setUsername(value);
    setActiveField('password');
  };

  const handlePasswordSubmit = async (value: string) => {
    setPassword(value);
    if (!username.trim() || !value.trim()) return;
    const success = await login(username, value);
    if (success) {
      navigate('main-menu');
    }
  };

  if (loading) {
    return (
      <Box flexDirection="column" alignItems="center" paddingY={4}>
        <LoadingSpinner label="Anmelden..." />
      </Box>
    );
  }

  return (
    <Box flexDirection="column" alignItems="center" paddingY={2}>
      <Box flexDirection="column" width={50} borderStyle="round" borderColor="cyan" paddingX={2} paddingY={1}>
        <Box marginBottom={1} justifyContent="center">
          <Text color="cyan" bold>
            Effigenix ERP – Anmeldung
          </Text>
        </Box>

        {error && (
          <Box marginBottom={1}>
            <ErrorDisplay message={error} onDismiss={clearError} />
          </Box>
        )}

        <Box flexDirection="column" gap={1}>
          <Box flexDirection="column">
            <Text color={activeField === 'username' ? 'cyan' : 'gray'}>Benutzername</Text>
            <Box>
              <Text color="gray"> › </Text>
              <TextInput
                value={username}
                onChange={setUsername}
                onSubmit={handleUsernameSubmit}
                focus={activeField === 'username'}
                placeholder="admin"
              />
            </Box>
          </Box>

          <Box flexDirection="column">
            <Text color={activeField === 'password' ? 'cyan' : 'gray'}>Passwort</Text>
            <Box>
              <Text color="gray"> › </Text>
              <TextInput
                value={password}
                onChange={setPassword}
                onSubmit={(v) => void handlePasswordSubmit(v)}
                focus={activeField === 'password'}
                mask="*"
                placeholder="••••••••"
              />
            </Box>
          </Box>
        </Box>

        <Box marginTop={1}>
          <Text color="gray" dimColor>
            Tab/↑↓ wechseln · Enter bestätigen
          </Text>
        </Box>
      </Box>
    </Box>
  );
}
