import React, { useEffect, useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../state/navigation-context.js';
import { useProductionOrders } from '../../hooks/useProductionOrders.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, PRIORITY_LABELS } from '@effigenix/api-client';
import type { UoM, Priority, RecipeSummaryDTO } from '@effigenix/api-client';

type Field = 'recipe' | 'quantity' | 'unit' | 'plannedDate' | 'priority' | 'notes';
const FIELDS: Field[] = ['recipe', 'quantity', 'unit', 'plannedDate', 'priority', 'notes'];

const FIELD_LABELS: Record<Field, string> = {
  recipe: 'Rezept (↑↓ auswählen)',
  quantity: 'Geplante Menge *',
  unit: 'Mengeneinheit * (←→ wechseln)',
  plannedDate: 'Geplantes Datum * (YYYY-MM-DD)',
  priority: 'Priorität (←→ wechseln)',
  notes: 'Notizen (optional)',
};

const PRIORITY_VALUES: Priority[] = ['LOW', 'NORMAL', 'HIGH', 'URGENT'];

export function ProductionOrderCreateScreen() {
  const { back } = useNavigation();
  const { createProductionOrder, releaseProductionOrder, productionOrder, loading, error, clearError } = useProductionOrders();
  const { recipes, fetchRecipes } = useRecipes();

  const [quantity, setQuantity] = useState('');
  const [uomIdx, setUomIdx] = useState(0);
  const [plannedDate, setPlannedDate] = useState('');
  const [priorityIdx, setPriorityIdx] = useState(1); // NORMAL default
  const [notes, setNotes] = useState('');
  const [recipeIdx, setRecipeIdx] = useState(0);
  const [activeField, setActiveField] = useState<Field>('recipe');
  const [fieldErrors, setFieldErrors] = useState<Partial<Record<Field, string>>>({});
  const [success, setSuccess] = useState(false);
  const [released, setReleased] = useState(false);

  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 (!plannedDate.trim() || !/^\d{4}-\d{2}-\d{2}$/.test(plannedDate)) errors.plannedDate = 'Format: YYYY-MM-DD';
    setFieldErrors(errors);
    if (Object.keys(errors).length > 0) return;

    const recipe = recipes[recipeIdx] as RecipeSummaryDTO;
    const result = await createProductionOrder({
      recipeId: recipe.id,
      plannedQuantity: quantity.trim(),
      plannedQuantityUnit: UOM_VALUES[uomIdx] as string,
      plannedDate: plannedDate.trim(),
      priority: PRIORITY_VALUES[priorityIdx] as string,
      ...(notes.trim() ? { notes: notes.trim() } : {}),
    });
    if (result) setSuccess(true);
  };

  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 (released) {
      if (key.return || key.escape) back();
      return;
    }

    if (success) {
      if (_input.toLowerCase() === 'f' && productionOrder?.id) {
        const orderId = productionOrder.id;
        void (async () => {
          const result = await releaseProductionOrder(orderId);
          if (result) setReleased(true);
        })();
        return;
      }
      if (key.escape) back();
      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 (activeField === 'priority') {
      if (key.leftArrow || key.rightArrow) {
        const dir = key.rightArrow ? 1 : -1;
        setPriorityIdx((i) => (i + dir + PRIORITY_VALUES.length) % PRIORITY_VALUES.length);
        return;
      }
      if (key.return) {
        handleFieldSubmit('priority')('');
        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="Produktionsauftrag wird erstellt..." />
      </Box>
    );
  }

  if (released) {
    return (
      <Box flexDirection="column" gap={1} paddingY={1}>
        <Text color="green" bold>Produktionsauftrag freigegeben!</Text>
        {productionOrder && (
          <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={1}>
            <Box><Text color="gray">ID:       </Text><Text>{productionOrder.id}</Text></Box>
            <Box><Text color="gray">Status:   </Text><Text color="green">{productionOrder.status}</Text></Box>
          </Box>
        )}
        <Text color="gray" dimColor>Enter/Escape zum Zurückkehren</Text>
      </Box>
    );
  }

  if (success) {
    return (
      <Box flexDirection="column" gap={1} paddingY={1}>
        <Text color="green" bold>Produktionsauftrag erfolgreich erstellt!</Text>
        {productionOrder && (
          <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={1}>
            <Box><Text color="gray">ID:       </Text><Text>{productionOrder.id}</Text></Box>
            <Box><Text color="gray">Rezept:   </Text><Text>{productionOrder.recipeId}</Text></Box>
            <Box><Text color="gray">Menge:    </Text><Text>{productionOrder.plannedQuantity} {productionOrder.plannedQuantityUnit}</Text></Box>
            <Box><Text color="gray">Status:   </Text><Text>{productionOrder.status}</Text></Box>
          </Box>
        )}
        <Text color="gray" dimColor>[F] Freigeben · Escape Zurück</Text>
      </Box>
    );
  }

  const uomLabel = UOM_LABELS[UOM_VALUES[uomIdx] as UoM] ?? UOM_VALUES[uomIdx];
  const priorityLabel = PRIORITY_LABELS[PRIORITY_VALUES[priorityIdx] as Priority] ?? PRIORITY_VALUES[priorityIdx];

  return (
    <Box flexDirection="column" gap={1}>
      <Text color="cyan" bold>Neuen Produktionsauftrag anlegen</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>

        {/* Planned Date */}
        <FormInput
          label={FIELD_LABELS.plannedDate}
          value={plannedDate}
          onChange={setPlannedDate}
          onSubmit={handleFieldSubmit('plannedDate')}
          focus={activeField === 'plannedDate'}
          placeholder="2026-03-01"
          {...(fieldErrors.plannedDate ? { error: fieldErrors.plannedDate } : {})}
        />

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

        {/* Notes */}
        <FormInput
          label={FIELD_LABELS.notes}
          value={notes}
          onChange={setNotes}
          onSubmit={handleFieldSubmit('notes')}
          focus={activeField === 'notes'}
          placeholder="Optionale Notizen..."
        />
      </Box>

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