import React, { useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../../state/navigation-context.js';
import { useCategories } from '../../../hooks/useCategories.js';
import { FormInput } from '../../shared/FormInput.js';
import { LoadingSpinner } from '../../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../../shared/ErrorDisplay.js';

type Field = 'name' | 'description';
const FIELDS: Field[] = ['name', 'description'];

export function CategoryCreateScreen() {
  const { replace, back } = useNavigation();
  const { createCategory, loading, error, clearError } = useCategories();

  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [activeField, setActiveField] = useState<Field>('name');
  const [nameError, setNameError] = 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.escape) back();
  });

  const handleSubmit = async () => {
    setNameError(null);
    if (!name.trim()) {
      setNameError('Name ist erforderlich.');
      return;
    }
    const cat = await createCategory(name.trim(), description.trim() || undefined);
    if (cat) replace('category-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();
    }
  };

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

  return (
    <Box flexDirection="column" gap={1}>
      <Text color="cyan" bold>Neue Produktkategorie</Text>

      {error && <ErrorDisplay message={error} onDismiss={clearError} />}

      <Box flexDirection="column" gap={1} width={60}>
        <FormInput
          label="Name *"
          value={name}
          onChange={setName}
          onSubmit={handleFieldSubmit('name')}
          focus={activeField === 'name'}
          placeholder="z.B. Obst & Gemüse"
          {...(nameError !== null ? { error: nameError } : {})}
        />
        <FormInput
          label="Beschreibung"
          value={description}
          onChange={setDescription}
          onSubmit={handleFieldSubmit('description')}
          focus={activeField === 'description'}
          placeholder="(optional)"
        />
      </Box>

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