import React, { useEffect, 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 { 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' | 'articleNumber' | 'categoryId' | 'unit' | 'priceModel' | 'price';
const FIELDS: Field[] = ['name', 'articleNumber', 'categoryId', 'unit', 'priceModel', 'price'];

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 ArticleCreateScreen() {
  const { replace, back } = useNavigation();
  const { createArticle, loading, error, clearError } = useArticles();
  const { categories, fetchCategories } = useCategories();

  const [name, setName] = useState('');
  const [articleNumber, setArticleNumber] = useState('');
  const [categoryIndex, setCategoryIndex] = useState(0);
  const [unitIndex, setUnitIndex] = useState(0);
  const [price, setPrice] = useState('');
  const [activeField, setActiveField] = useState<Field>('name');
  const [fieldErrors, setFieldErrors] = useState<Partial<Record<Field, string>>>({});

  useEffect(() => { void fetchCategories(); }, [fetchCategories]);

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

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

    if (activeField === 'categoryId') {
      if (key.leftArrow) setCategoryIndex((i) => Math.max(0, i - 1));
      if (key.rightArrow) setCategoryIndex((i) => Math.min(categories.length - 1, i + 1));
    }
    if (activeField === 'unit') {
      if (key.leftArrow) {
        const newIdx = Math.max(0, unitIndex - 1);
        setUnitIndex(newIdx);
      }
      if (key.rightArrow) {
        const newIdx = Math.min(UNITS.length - 1, unitIndex + 1);
        setUnitIndex(newIdx);
      }
    }

    if (key.tab || key.downArrow) {
      setActiveField((f) => {
        const idx = FIELDS.indexOf(f);
        return FIELDS[(idx + 1) % FIELDS.length] ?? f;
      });
    }
    if (key.upArrow && activeField !== 'unit' && activeField !== 'categoryId') {
      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 (!name.trim()) errors.name = 'Name ist erforderlich.';
    if (!articleNumber.trim()) errors.articleNumber = 'Artikelnummer ist erforderlich.';
    if (categories.length === 0) errors.categoryId = 'Keine Kategorien verfügbar.';
    const priceNum = parseFloat(price.replace(',', '.'));
    if (isNaN(priceNum) || priceNum <= 0) errors.price = 'Gültiger Preis erforderlich.';
    setFieldErrors(errors);
    if (Object.keys(errors).length > 0) return;

    const cat = categories[categoryIndex];
    if (!cat) return;

    const result = await createArticle({
      name: name.trim(),
      articleNumber: articleNumber.trim(),
      categoryId: cat.id,
      unit: selectedUnit,
      priceModel: autoModel,
      price: priceNum,
    });
    if (result) replace('article-list');
  };

  if (loading) return <Box paddingY={2}><LoadingSpinner label="Artikel wird angelegt..." /></Box>;

  const selectedCategory = categories[categoryIndex];

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

      <Box flexDirection="column" gap={1} width={60}>
        <FormInput
          label="Name *"
          value={name}
          onChange={setName}
          onSubmit={() => setActiveField('articleNumber')}
          focus={activeField === 'name'}
          {...(fieldErrors.name ? { error: fieldErrors.name } : {})}
        />
        <FormInput
          label="Artikelnummer *"
          value={articleNumber}
          onChange={setArticleNumber}
          onSubmit={() => setActiveField('categoryId')}
          focus={activeField === 'articleNumber'}
          placeholder="z.B. OG-001"
          {...(fieldErrors.articleNumber ? { error: fieldErrors.articleNumber } : {})}
        />

        {/* Category Selector */}
        <Box flexDirection="column">
          <Text color={activeField === 'categoryId' ? 'cyan' : 'gray'}>Kategorie *</Text>
          <Box gap={1}>
            <Text color={activeField === 'categoryId' ? 'cyan' : 'gray'}>{'< '}</Text>
            <Text color={activeField === 'categoryId' ? 'white' : 'gray'}>
              {selectedCategory?.name ?? 'Keine Kategorien'}
            </Text>
            <Text color={activeField === 'categoryId' ? 'cyan' : 'gray'}>{' >'}</Text>
          </Box>
          {fieldErrors.categoryId && <Text color="red">{fieldErrors.categoryId}</Text>}
          {activeField === 'categoryId' && <Text color="gray" dimColor>←→ Kategorie wechseln · Tab weiter</Text>}
        </Box>

        {/* Unit Selector */}
        <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 wechseln · Tab weiter</Text>}
        </Box>

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

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