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

type Field = 'stepNumber' | 'description' | 'durationMinutes' | 'temperatureCelsius';
const FIELDS: Field[] = ['stepNumber', 'description', 'durationMinutes', 'temperatureCelsius'];

const FIELD_LABELS: Record<Field, string> = {
  stepNumber: 'Schrittnummer (optional)',
  description: 'Beschreibung *',
  durationMinutes: 'Dauer in Minuten (optional)',
  temperatureCelsius: 'Temperatur in °C (optional)',
};

function errorMessage(err: unknown): string {
  return err instanceof Error ? err.message : 'Unbekannter Fehler';
}

export function AddProductionStepScreen() {
  const { params, replace, back } = useNavigation();
  const recipeId = params['recipeId'] ?? '';

  const [values, setValues] = useState<Record<Field, string>>({
    stepNumber: '', description: '', durationMinutes: '', temperatureCelsius: '',
  });
  const [activeField, setActiveField] = useState<Field>('stepNumber');
  const [fieldErrors, setFieldErrors] = useState<Partial<Record<Field, string>>>({});
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const setField = (field: Field) => (value: string) => {
    setValues((v) => ({ ...v, [field]: value }));
  };

  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 () => {
    const errors: Partial<Record<Field, string>> = {};
    if (!values.description.trim()) errors.description = 'Beschreibung ist erforderlich.';
    if (values.stepNumber.trim() && (!Number.isInteger(Number(values.stepNumber)) || Number(values.stepNumber) < 1)) {
      errors.stepNumber = 'Muss eine positive Ganzzahl sein.';
    }
    if (values.durationMinutes.trim() && (!Number.isInteger(Number(values.durationMinutes)) || Number(values.durationMinutes) < 1)) {
      errors.durationMinutes = 'Muss eine positive Ganzzahl sein.';
    }
    if (values.temperatureCelsius.trim() && isNaN(Number(values.temperatureCelsius))) {
      errors.temperatureCelsius = 'Muss eine Zahl sein.';
    }
    setFieldErrors(errors);
    if (Object.keys(errors).length > 0) return;

    setLoading(true);
    setError(null);
    try {
      await client.recipes.addProductionStep(recipeId, {
        description: values.description.trim(),
        ...(values.stepNumber.trim() ? { stepNumber: Number(values.stepNumber) } : {}),
        ...(values.durationMinutes.trim() ? { durationMinutes: Number(values.durationMinutes) } : {}),
        ...(values.temperatureCelsius.trim() ? { temperatureCelsius: Number(values.temperatureCelsius) } : {}),
      });
      replace('recipe-detail', { recipeId });
    } catch (err: unknown) {
      setError(errorMessage(err));
      setLoading(false);
    }
  };

  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 (!recipeId) return <ErrorDisplay message="Keine Rezept-ID vorhanden." onDismiss={back} />;
  if (loading) return <Box paddingY={2}><LoadingSpinner label="Produktionsschritt wird hinzugefügt..." /></Box>;

  return (
    <Box flexDirection="column" gap={1}>
      <Text color="cyan" bold>Produktionsschritt hinzufügen</Text>
      {error && <ErrorDisplay message={error} onDismiss={() => setError(null)} />}

      <Box flexDirection="column" gap={1} width={60}>
        {FIELDS.map((field) => (
          <FormInput
            key={field}
            label={FIELD_LABELS[field]}
            value={values[field]}
            onChange={setField(field)}
            onSubmit={handleFieldSubmit(field)}
            focus={activeField === field}
            {...(fieldErrors[field] ? { error: fieldErrors[field] } : {})}
          />
        ))}
      </Box>

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