import React, { useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../state/navigation-context.js';
import { useStorageLocations } from '../../hooks/useStorageLocations.js';
import { FormInput } from '../shared/FormInput.js';
import { LoadingSpinner } from '../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../shared/ErrorDisplay.js';
import { STORAGE_TYPE_LABELS } from '@effigenix/api-client';
import type { StorageType } from '@effigenix/api-client';

type Field = 'name' | 'storageType' | 'minTemperature' | 'maxTemperature';
const FIELDS: Field[] = ['name', 'storageType', 'minTemperature', 'maxTemperature'];

const FIELD_LABELS: Record<Field, string> = {
  name: 'Name *',
  storageType: 'Lagertyp * (←→ wechseln)',
  minTemperature: 'Min. Temperatur (°C)',
  maxTemperature: 'Max. Temperatur (°C)',
};

const STORAGE_TYPES: StorageType[] = ['COLD_ROOM', 'FREEZER', 'DRY_STORAGE', 'DISPLAY_COUNTER', 'PRODUCTION_AREA'];

export function StorageLocationCreateScreen() {
  const { replace, back } = useNavigation();
  const { createStorageLocation, loading, error, clearError } = useStorageLocations();

  const [values, setValues] = useState<Record<Field, string>>({
    name: '',
    storageType: 'DRY_STORAGE',
    minTemperature: '',
    maxTemperature: '',
  });
  const [activeField, setActiveField] = useState<Field>('name');
  const [fieldErrors, setFieldErrors] = useState<Partial<Record<Field, string>>>({});

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

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

    if (activeField === 'storageType') {
      if (key.leftArrow || key.rightArrow) {
        const idx = STORAGE_TYPES.indexOf(values.storageType as StorageType);
        const dir = key.rightArrow ? 1 : -1;
        const next = STORAGE_TYPES[(idx + dir + STORAGE_TYPES.length) % STORAGE_TYPES.length];
        if (next) setValues((v) => ({ ...v, storageType: next }));
        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.name.trim()) errors.name = 'Name ist erforderlich.';
    if (!values.storageType) errors.storageType = 'Lagertyp ist erforderlich.';
    setFieldErrors(errors);
    if (Object.keys(errors).length > 0) return;

    const result = await createStorageLocation({
      name: values.name.trim(),
      storageType: values.storageType,
      ...(values.minTemperature.trim() ? { minTemperature: values.minTemperature.trim() } : {}),
      ...(values.maxTemperature.trim() ? { maxTemperature: values.maxTemperature.trim() } : {}),
    });
    if (result) replace('storage-location-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="Lagerort wird angelegt..." />
      </Box>
    );
  }

  const storageTypeLabel = STORAGE_TYPE_LABELS[values.storageType as StorageType] ?? values.storageType;

  return (
    <Box flexDirection="column" gap={1}>
      <Text color="cyan" bold>Neuer Lagerort</Text>
      {error && <ErrorDisplay message={error} onDismiss={clearError} />}

      <Box flexDirection="column" gap={1} width={60}>
        {FIELDS.map((field) => {
          if (field === 'storageType') {
            return (
              <Box key={field} flexDirection="column">
                <Text color={activeField === field ? 'cyan' : 'gray'}>
                  {FIELD_LABELS[field]}: <Text bold color="white">{storageTypeLabel}</Text>
                </Text>
                {fieldErrors[field] && <Text color="red">{fieldErrors[field]}</Text>}
              </Box>
            );
          }
          return (
            <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 · ←→ Lagertyp · Enter auf letztem Feld speichern · Escape Abbrechen
        </Text>
      </Box>
    </Box>
  );
}
