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

const UNITS: Unit[] = ['PIECE_FIXED', 'KG', 'HUNDRED_GRAM', 'PIECE_VARIABLE'];
const UNIT_PRICE_MODEL: Record<Unit, PriceModel> = {
  PIECE_FIXED: 'FIXED',
  KG: 'WEIGHT_BASED',
  HUNDRED_GRAM: 'WEIGHT_BASED',
  PIECE_VARIABLE: 'WEIGHT_BASED',
};

export function AddSalesUnitScreen() {
  const { params, replace, back } = useNavigation();
  const articleId = params['articleId'] ?? '';
  const { addSalesUnit, loading, error, clearError } = useArticles();

  const [unitIndex, setUnitIndex] = useState(0);
  const [price, setPrice] = useState('');
  const [activeField, setActiveField] = useState<'unit' | 'price'>('unit');
  const [priceError, setPriceError] = useState<string | null>(null);

  const selectedUnit = UNITS[unitIndex] ?? 'PIECE_FIXED';
  const autoModel = UNIT_PRICE_MODEL[selectedUnit];

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

    if (activeField === 'unit') {
      if (key.leftArrow) setUnitIndex((i) => Math.max(0, i - 1));
      if (key.rightArrow) setUnitIndex((i) => Math.min(UNITS.length - 1, i + 1));
      if (key.tab || key.downArrow || key.return) setActiveField('price');
    }

    if (key.upArrow && activeField === 'price') setActiveField('unit');
    if (key.escape) back();
  });

  const handleSubmit = async () => {
    const priceNum = parseFloat(price.replace(',', '.'));
    if (isNaN(priceNum) || priceNum <= 0) {
      setPriceError('Gültiger Preis erforderlich.');
      return;
    }
    setPriceError(null);
    const updated = await addSalesUnit(articleId, { unit: selectedUnit, priceModel: autoModel, price: priceNum });
    if (updated) replace('article-detail', { articleId });
  };

  if (loading) return <Box paddingY={2}><LoadingSpinner label="Verkaufseinheit wird hinzugefügt..." /></Box>;

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

      <Box flexDirection="column" gap={1} width={60}>
        <Box flexDirection="column">
          <Text color={activeField === 'unit' ? 'cyan' : 'gray'}>Einheit *</Text>
          <Box gap={1}>
            <Text color={activeField === 'unit' ? 'cyan' : 'gray'}>{'< '}</Text>
            <Text color={activeField === 'unit' ? 'white' : 'gray'}>{UNIT_LABELS[selectedUnit]}</Text>
            <Text color={activeField === 'unit' ? 'cyan' : 'gray'}>{' >'}</Text>
            <Text color="gray" dimColor>→ {PRICE_MODEL_LABELS[autoModel]}</Text>
          </Box>
          {activeField === 'unit' && <Text color="gray" dimColor>←→ Einheit · Tab/Enter weiter</Text>}
        </Box>

        <FormInput
          label="Preis (€) *"
          value={price}
          onChange={setPrice}
          onSubmit={() => void handleSubmit()}
          focus={activeField === 'price'}
          placeholder="z.B. 2.49"
          {...(priceError ? { error: priceError } : {})}
        />
      </Box>

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