import React, { useEffect, useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../state/navigation-context.js';
import { useStockMovements } from '../../hooks/useStockMovements.js';
import { LoadingSpinner } from '../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../shared/ErrorDisplay.js';
import { MOVEMENT_TYPE_LABELS, MOVEMENT_DIRECTION_LABELS } from '@effigenix/api-client';
import type { MovementType, MovementDirection, StockMovementFilter } from '@effigenix/api-client';

const DIRECTION_COLORS: Record<string, string> = {
  IN: 'green',
  OUT: 'red',
};

const TYPE_FILTER_OPTIONS: { key: string; label: string; value: string | undefined }[] = [
  { key: 'a', label: 'ALLE', value: undefined },
  { key: '1', label: 'Wareneingang', value: 'GOODS_RECEIPT' },
  { key: '2', label: 'Prod.-Ausstoß', value: 'PRODUCTION_OUTPUT' },
  { key: '3', label: 'Prod.-Verbrauch', value: 'PRODUCTION_CONSUMPTION' },
  { key: '4', label: 'Verkauf', value: 'SALE' },
  { key: '5', label: 'Retoure', value: 'RETURN' },
  { key: '6', label: 'Ausschuss', value: 'WASTE' },
  { key: '7', label: 'Korrektur', value: 'ADJUSTMENT' },
  { key: '8', label: 'Umlagerung', value: 'INTER_BRANCH_TRANSFER' },
];

export function StockMovementListScreen() {
  const { navigate, back, params } = useNavigation();
  const { movements, loading, error, fetchMovements, clearError } = useStockMovements();
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [typeFilter, setTypeFilter] = useState<string | undefined>(undefined);

  const stockId = params.stockId;

  useEffect(() => {
    const filter: StockMovementFilter = {};
    if (stockId) filter.stockId = stockId;
    if (typeFilter) filter.movementType = typeFilter;
    void fetchMovements(filter);
  }, [fetchMovements, stockId, typeFilter]);

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

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

    if (key.return && movements.length > 0) {
      const movement = movements[selectedIndex];
      if (movement) navigate('stock-movement-detail', { movementId: movement.id });
    }
    if (input === 'n') navigate('stock-movement-record', stockId ? { stockId } : {});
    if (input === 'r') {
      const filter: StockMovementFilter = {};
      if (stockId) filter.stockId = stockId;
      if (typeFilter) filter.movementType = typeFilter;
      void fetchMovements(filter);
    }
    if (key.backspace || key.escape) back();

    for (const opt of TYPE_FILTER_OPTIONS) {
      if (input === opt.key) {
        setTypeFilter(opt.value);
        setSelectedIndex(0);
        break;
      }
    }
  });

  const activeFilterLabel = TYPE_FILTER_OPTIONS.find((f) => f.value === typeFilter)?.label ?? 'ALLE';

  return (
    <Box flexDirection="column" gap={1}>
      <Box gap={2}>
        <Text color="cyan" bold>Bestandsbewegungen</Text>
        <Text color="gray" dimColor>({movements.length})</Text>
        <Text color="gray" dimColor>Filter: </Text>
        <Text color="yellow" bold>{activeFilterLabel}</Text>
      </Box>

      {loading && <LoadingSpinner label="Lade Bewegungen..." />}
      {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>{'  Typ'.padEnd(22)}</Text>
            <Text color="gray" bold>{'Richtung'.padEnd(10)}</Text>
            <Text color="gray" bold>{'Menge'.padEnd(16)}</Text>
            <Text color="gray" bold>{'Charge'.padEnd(16)}</Text>
            <Text color="gray" bold>Zeitpunkt</Text>
          </Box>
          {movements.length === 0 && (
            <Box paddingX={1} paddingY={1}>
              <Text color="gray" dimColor>Keine Bewegungen gefunden.</Text>
            </Box>
          )}
          {movements.map((m, index) => {
            const isSelected = index === selectedIndex;
            const textColor = isSelected ? 'cyan' : 'white';
            const typeLabel = MOVEMENT_TYPE_LABELS[m.movementType as MovementType] ?? m.movementType;
            const dirLabel = MOVEMENT_DIRECTION_LABELS[m.direction as MovementDirection] ?? m.direction;
            const dirColor = isSelected ? 'cyan' : (DIRECTION_COLORS[m.direction] ?? 'white');
            const qty = `${m.quantityAmount} ${m.quantityUnit}`;
            const dateStr = m.performedAt ? new Date(m.performedAt).toLocaleString('de-DE', { dateStyle: 'short', timeStyle: 'short' }) : '';
            return (
              <Box key={m.id} paddingX={1}>
                <Text color={textColor}>{isSelected ? '▶ ' : '  '}</Text>
                <Text color={textColor}>{typeLabel.substring(0, 18).padEnd(19)}</Text>
                <Text color={dirColor}>{dirLabel.padEnd(10)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{qty.substring(0, 14).padEnd(16)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{(m.batchId ?? '').substring(0, 14).padEnd(16)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{dateStr}</Text>
              </Box>
            );
          })}
        </Box>
      )}

      <Box marginTop={1}>
        <Text color="gray" dimColor>
          ↑↓ nav · Enter Details · [n] Neu · [r] Aktualisieren · [a] Alle [1-8] Typ-Filter · Backspace Zurück
        </Text>
      </Box>
    </Box>
  );
}
