import React, { useEffect, useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../state/navigation-context.js';
import { useBatches } from '../../hooks/useBatches.js';
import { useRecipes } from '../../hooks/useRecipes.js';
import { FormInput } from '../shared/FormInput.js';
import { LoadingSpinner } from '../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../shared/ErrorDisplay.js';
import { UOM_VALUES, UOM_LABELS } from '@effigenix/api-client';
import type { UoM, RecipeSummaryDTO } from '@effigenix/api-client';

type Field = 'recipe' | 'quantity' | 'unit' | 'productionDate' | 'bestBeforeDate';
const FIELDS: Field[] = ['recipe', 'quantity', 'unit', 'productionDate', 'bestBeforeDate'];

const FIELD_LABELS: Record<Field, string> = {
  recipe: 'Rezept (↑↓ auswählen)',
  quantity: 'Geplante Menge *',
  unit: 'Mengeneinheit * (←→ wechseln)',
  productionDate: 'Produktionsdatum * (YYYY-MM-DD)',
  bestBeforeDate: 'MHD * (YYYY-MM-DD)',
};

export function BatchPlanScreen() {
  const { replace, back } = useNavigation();
  const { planBatch, loading, error, clearError } = useBatches();
  const { recipes, fetchRecipes } = useRecipes();

  const [quantity, setQuantity] = useState('');
  const [uomIdx, setUomIdx] = useState(0);
  const [productionDate, setProductionDate] = useState('');
  const [bestBeforeDate, setBestBeforeDate] = useState('');
  const [recipeIdx, setRecipeIdx] = useState(0);
  const [activeField, setActiveField] = useState<Field>('recipe');
  const [fieldErrors, setFieldErrors] = useState<Partial<Record<Field, string>>>({});

  useEffect(() => {
    void fetchRecipes('ACTIVE');
  }, [fetchRecipes]);

  const handleSubmit = async () => {
    const errors: Partial<Record<Field, string>> = {};
    if (recipes.length === 0) errors.recipe = 'Kein aktives Rezept verfügbar.';
    if (!quantity.trim()) errors.quantity = 'Menge ist erforderlich.';
    if (!productionDate.trim() || !/^\d{4}-\d{2}-\d{2}$/.test(productionDate)) errors.productionDate = 'Format: YYYY-MM-DD';
    if (!bestBeforeDate.trim() || !/^\d{4}-\d{2}-\d{2}$/.test(bestBeforeDate)) errors.bestBeforeDate = 'Format: YYYY-MM-DD';
    setFieldErrors(errors);
    if (Object.keys(errors).length > 0) return;

    const recipe = recipes[recipeIdx] as RecipeSummaryDTO;
    const result = await planBatch({
      recipeId: recipe.id,
      plannedQuantity: quantity.trim(),
      plannedQuantityUnit: UOM_VALUES[uomIdx] as string,
      productionDate: productionDate.trim(),
      bestBeforeDate: bestBeforeDate.trim(),
    });
    if (result?.id) replace('batch-detail', { batchId: result.id });
  };

  const handleFieldSubmit = (field: Field) => (_value: string) => {
    const idx = FIELDS.indexOf(field);
    if (idx < FIELDS.length - 1) {
      setActiveField(FIELDS[idx + 1] ?? field);
    } else {
      void handleSubmit();
    }
  };

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

    if (activeField === 'recipe') {
      if (key.upArrow) setRecipeIdx((i) => Math.max(0, i - 1));
      if (key.downArrow) setRecipeIdx((i) => Math.min(recipes.length - 1, i + 1));
      if (key.return || key.tab) setActiveField('quantity');
      if (key.escape) back();
      return;
    }

    if (activeField === 'unit') {
      if (key.leftArrow || key.rightArrow) {
        const dir = key.rightArrow ? 1 : -1;
        setUomIdx((i) => (i + dir + UOM_VALUES.length) % UOM_VALUES.length);
        return;
      }
      if (key.return) {
        handleFieldSubmit('unit')('');
        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();
  });

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

  const uomLabel = UOM_LABELS[UOM_VALUES[uomIdx] as UoM] ?? UOM_VALUES[uomIdx];

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

      <Box flexDirection="column" gap={1} width={60}>
        {/* Recipe selector */}
        <Box flexDirection="column">
          <Text color={activeField === 'recipe' ? 'cyan' : 'gray'}>{FIELD_LABELS.recipe}</Text>
          {fieldErrors.recipe && <Text color="red">{fieldErrors.recipe}</Text>}
          <Box flexDirection="column" borderStyle="round" borderColor={activeField === 'recipe' ? 'cyan' : 'gray'} paddingX={1}>
            {recipes.length === 0 ? (
              <Text color="gray" dimColor>Keine aktiven Rezepte gefunden.</Text>
            ) : (
              recipes.slice(Math.max(0, recipeIdx - 3), recipeIdx + 4).map((r, i) => {
                const actualIdx = Math.max(0, recipeIdx - 3) + i;
                const isSelected = actualIdx === recipeIdx;
                return (
                  <Text key={r.id} color={isSelected ? 'cyan' : 'white'}>
                    {isSelected ? '▶ ' : '  '}{r.name} (v{r.version})
                  </Text>
                );
              })
            )}
          </Box>
        </Box>

        {/* Quantity */}
        <FormInput
          label={FIELD_LABELS.quantity}
          value={quantity}
          onChange={setQuantity}
          onSubmit={handleFieldSubmit('quantity')}
          focus={activeField === 'quantity'}
          {...(fieldErrors.quantity ? { error: fieldErrors.quantity } : {})}
        />

        {/* Unit */}
        <Box flexDirection="column">
          <Text color={activeField === 'unit' ? 'cyan' : 'gray'}>
            {FIELD_LABELS.unit}: <Text bold color="white">{activeField === 'unit' ? `< ${uomLabel} >` : uomLabel}</Text>
          </Text>
        </Box>

        {/* Production Date */}
        <FormInput
          label={FIELD_LABELS.productionDate}
          value={productionDate}
          onChange={setProductionDate}
          onSubmit={handleFieldSubmit('productionDate')}
          focus={activeField === 'productionDate'}
          placeholder="2025-01-15"
          {...(fieldErrors.productionDate ? { error: fieldErrors.productionDate } : {})}
        />

        {/* Best Before Date */}
        <FormInput
          label={FIELD_LABELS.bestBeforeDate}
          value={bestBeforeDate}
          onChange={setBestBeforeDate}
          onSubmit={handleFieldSubmit('bestBeforeDate')}
          focus={activeField === 'bestBeforeDate'}
          placeholder="2025-03-15"
          {...(fieldErrors.bestBeforeDate ? { error: fieldErrors.bestBeforeDate } : {})}
        />
      </Box>

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