import React, { useEffect, useState, useCallback } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../state/navigation-context.js';
import { useProductionOrders } from '../../hooks/useProductionOrders.js';
import { LoadingSpinner } from '../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../shared/ErrorDisplay.js';
import { PRODUCTION_ORDER_STATUS_LABELS, PRIORITY_LABELS } from '@effigenix/api-client';
import type { ProductionOrderStatus, Priority, ProductionOrderFilter } from '@effigenix/api-client';

const STATUS_FILTER_KEYS: Record<string, { status?: ProductionOrderStatus; label: string }> = {
  a: { label: 'Alle' },
  p: { status: 'PLANNED', label: 'Geplant' },
  f: { status: 'RELEASED', label: 'Freigegeben' },
  i: { status: 'IN_PROGRESS', label: 'In Produktion' },
  c: { status: 'COMPLETED', label: 'Abgeschlossen' },
  x: { status: 'CANCELLED', label: 'Storniert' },
};

const STATUS_COLORS: Record<string, string> = {
  PLANNED: 'gray',
  RELEASED: 'yellow',
  IN_PROGRESS: 'blue',
  COMPLETED: 'green',
  CANCELLED: 'red',
};

export function ProductionOrderListScreen() {
  const { navigate, back } = useNavigation();
  const { productionOrders, loading, error, fetchProductionOrders, clearError } = useProductionOrders();
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [activeFilter, setActiveFilter] = useState<{ status?: ProductionOrderStatus; label: string }>({ label: 'Alle' });

  const loadWithFilter = useCallback((filter: { status?: ProductionOrderStatus; label: string }) => {
    setActiveFilter(filter);
    setSelectedIndex(0);
    const f: ProductionOrderFilter | undefined = filter.status ? { status: filter.status } : undefined;
    void fetchProductionOrders(f);
  }, [fetchProductionOrders]);

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

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

    if (key.upArrow) setSelectedIndex((i) => Math.max(0, i - 1));
    if (key.downArrow) setSelectedIndex((i) => Math.min(productionOrders.length - 1, i + 1));

    if (key.return && productionOrders.length > 0) {
      const order = productionOrders[selectedIndex];
      if (order?.id) navigate('production-order-detail', { orderId: order.id });
    }
    if (input === 'n') navigate('production-order-create');
    if (input === 'r') loadWithFilter(activeFilter);

    const filterDef = STATUS_FILTER_KEYS[input];
    if (filterDef) loadWithFilter(filterDef);

    if (key.backspace || key.escape) back();
  });

  return (
    <Box flexDirection="column" gap={1}>
      <Box gap={2}>
        <Text color="cyan" bold>Produktionsaufträge</Text>
        <Text color="gray" dimColor>({productionOrders.length})</Text>
        {activeFilter.status && <Text color="yellow">[{activeFilter.label}]</Text>}
      </Box>

      {loading && <LoadingSpinner label="Lade Aufträge..." />}
      {error && !loading && <ErrorDisplay message={error} onDismiss={clearError} />}

      {!loading && !error && (
        <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={1}>
          <Box paddingX={1}>
            <Text color="gray" bold>{'  Rezept-ID'.padEnd(16)}</Text>
            <Text color="gray" bold>{'Menge'.padEnd(16)}</Text>
            <Text color="gray" bold>{'Datum'.padEnd(14)}</Text>
            <Text color="gray" bold>{'Priorität'.padEnd(12)}</Text>
            <Text color="gray" bold>Status</Text>
          </Box>
          {productionOrders.length === 0 && (
            <Box paddingX={1} paddingY={1}>
              <Text color="gray" dimColor>Keine Produktionsaufträge gefunden.</Text>
            </Box>
          )}
          {productionOrders.map((order, index) => {
            const isSelected = index === selectedIndex;
            const textColor = isSelected ? 'cyan' : 'white';
            const statusColor = STATUS_COLORS[order.status ?? ''] ?? 'white';
            const statusLabel = PRODUCTION_ORDER_STATUS_LABELS[(order.status ?? '') as ProductionOrderStatus] ?? order.status;
            const prioLabel = PRIORITY_LABELS[(order.priority ?? '') as Priority] ?? order.priority;
            const qty = `${order.plannedQuantity ?? ''} ${order.plannedQuantityUnit ?? ''}`;
            return (
              <Box key={order.id} paddingX={1}>
                <Text color={textColor}>{isSelected ? '▶ ' : '  '}</Text>
                <Text color={textColor}>{(order.recipeId ?? '').substring(0, 12).padEnd(13)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{qty.substring(0, 14).padEnd(16)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{(order.plannedDate ?? '').padEnd(14)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{(prioLabel ?? '').padEnd(12)}</Text>
                <Text color={isSelected ? 'cyan' : statusColor}>{statusLabel}</Text>
              </Box>
            );
          })}
        </Box>
      )}

      <Box marginTop={1}>
        <Text color="gray" dimColor>
          ↑↓ nav · Enter Details · [n] Neu · [r] Aktualisieren · [a]lle [p]lan [f]rei [i]n Prod [c]omp [x]storno · Bksp Zurück
        </Text>
      </Box>
    </Box>
  );
}
