import React, { useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../state/navigation-context.js';
import { useUsers } from '../../hooks/useUsers.js';
import { FormInput } from '../shared/FormInput.js';
import { LoadingSpinner } from '../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../shared/ErrorDisplay.js';
import { usernameSchema, emailSchema, passwordSchema } from '@effigenix/validation';

type Field = 'username' | 'email' | 'password' | 'roleName';
const FIELDS: Field[] = ['username', 'email', 'password', 'roleName'];

export function UserCreateScreen() {
  const { replace, back } = useNavigation();
  const { createUser, loading, error, clearError } = useUsers();

  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [roleName, setRoleName] = useState('');
  const [activeField, setActiveField] = useState<Field>('username');
  const [validationError, setValidationError] = useState<string | null>(null);
  const [usernameError, setUsernameError] = useState<string | null>(null);
  const [emailError, setEmailError] = useState<string | null>(null);
  const [passwordError, setPasswordError] = useState<string | null>(null);

  useInput((_input, key) => {
    if (loading) return;
    if (key.tab || key.downArrow) {
      setActiveField((f) => {
        const idx = FIELDS.indexOf(f);
        return FIELDS[(idx + 1) % FIELDS.length] ?? f;
      });
    }
    if (key.upArrow) {
      setActiveField((f) => {
        const idx = FIELDS.indexOf(f);
        return FIELDS[(idx - 1 + FIELDS.length) % FIELDS.length] ?? f;
      });
    }
    if (key.backspace && !key.meta) {
      // Only go back if no text input is focused and the fields are empty
    }
    if (key.escape) {
      back();
    }
  });

  const handleSubmit = async () => {
    setValidationError(null);
    setUsernameError(null);
    setEmailError(null);
    setPasswordError(null);

    const usernameResult = usernameSchema.safeParse(username.trim());
    const emailResult = emailSchema.safeParse(email.trim());
    const passwordResult = passwordSchema.safeParse(password.trim());

    let hasError = false;
    if (!usernameResult.success) {
      setUsernameError(usernameResult.error.errors[0]?.message ?? 'Ungültiger Benutzername');
      hasError = true;
    }
    if (!emailResult.success) {
      setEmailError(emailResult.error.errors[0]?.message ?? 'Ungültige E-Mail');
      hasError = true;
    }
    if (!passwordResult.success) {
      setPasswordError(passwordResult.error.errors[0]?.message ?? 'Ungültiges Passwort');
      hasError = true;
    }
    if (hasError) return;

    const user = await createUser(username.trim(), email.trim(), password.trim(), roleName.trim() || undefined);
    if (user) {
      replace('user-list');
    }
  };

  const handleFieldSubmit = (field: Field) => (value: string) => {
    const idx = FIELDS.indexOf(field);
    if (idx < FIELDS.length - 1) {
      setActiveField(FIELDS[idx + 1] ?? field);
    } else {
      void handleSubmit();
    }
    void value;
  };

  if (loading) {
    return (
      <Box flexDirection="column" alignItems="center" paddingY={2}>
        <LoadingSpinner label="Benutzer wird angelegt..." />
      </Box>
    );
  }

  const displayError = validationError ?? error;

  return (
    <Box flexDirection="column" gap={1}>
      <Text color="cyan" bold>
        Neuen Benutzer anlegen
      </Text>

      {displayError && (
        <ErrorDisplay
          message={displayError}
          onDismiss={() => {
            setValidationError(null);
            clearError();
          }}
        />
      )}

      <Box flexDirection="column" gap={1} width={60}>
        <FormInput
          label="Benutzername *"
          value={username}
          onChange={setUsername}
          onSubmit={handleFieldSubmit('username')}
          focus={activeField === 'username'}
          placeholder="admin"
          {...(usernameError !== null ? { error: usernameError } : {})}
        />
        <FormInput
          label="E-Mail *"
          value={email}
          onChange={setEmail}
          onSubmit={handleFieldSubmit('email')}
          focus={activeField === 'email'}
          placeholder="admin@example.com"
          {...(emailError !== null ? { error: emailError } : {})}
        />
        <FormInput
          label="Passwort *"
          value={password}
          onChange={setPassword}
          onSubmit={handleFieldSubmit('password')}
          focus={activeField === 'password'}
          mask="*"
          placeholder="••••••••"
          {...(passwordError !== null ? { error: passwordError } : {})}
        />
        <FormInput
          label="Rolle (optional)"
          value={roleName}
          onChange={setRoleName}
          onSubmit={handleFieldSubmit('roleName')}
          focus={activeField === 'roleName'}
          placeholder="ADMIN"
        />
      </Box>

      <Box marginTop={1}>
        <Text color="gray" dimColor>
          Tab/↑↓ Feld wechseln · Enter auf letztem Feld speichern · Escape Abbrechen
        </Text>
      </Box>
    </Box>
  );
}
