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 { LoadingSpinner } from '../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../shared/ErrorDisplay.js';
import { BATCH_STATUS_LABELS } from '@effigenix/api-client';
import type { BatchStatus } from '@effigenix/api-client';

const STATUS_FILTERS: { key: string; label: string; value: BatchStatus | undefined }[] = [
  { key: 'a', label: 'ALLE', value: undefined },
  { key: 'P', label: 'GEPLANT', value: 'PLANNED' },
  { key: 'I', label: 'IN PRODUKTION', value: 'IN_PRODUCTION' },
  { key: 'C', label: 'ABGESCHLOSSEN', value: 'COMPLETED' },
  { key: 'X', label: 'STORNIERT', value: 'CANCELLED' },
];

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

export function BatchListScreen() {
  const { navigate, back } = useNavigation();
  const { batches, loading, error, fetchBatches, clearError } = useBatches();
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [statusFilter, setStatusFilter] = useState<BatchStatus | undefined>(undefined);

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

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

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

    if (key.return && batches.length > 0) {
      const batch = batches[selectedIndex];
      if (batch?.id) navigate('batch-detail', { batchId: batch.id });
    }
    if (input === 'n') navigate('batch-plan');
    if (key.backspace || key.escape) back();

    for (const filter of STATUS_FILTERS) {
      if (input === filter.key) {
        setStatusFilter(filter.value);
        setSelectedIndex(0);
        break;
      }
    }
  });

  const activeFilterLabel = STATUS_FILTERS.find((f) => f.value === statusFilter)?.label ?? 'ALLE';

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

      {loading && <LoadingSpinner label="Lade Chargen..." />}
      {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>{'  Chargen-Nr.'.padEnd(18)}</Text>
            <Text color="gray" bold>{'Menge'.padEnd(14)}</Text>
            <Text color="gray" bold>{'Prod.-Datum'.padEnd(14)}</Text>
            <Text color="gray" bold>{'MHD'.padEnd(14)}</Text>
            <Text color="gray" bold>Status</Text>
          </Box>
          {batches.length === 0 && (
            <Box paddingX={1} paddingY={1}>
              <Text color="gray" dimColor>Keine Chargen gefunden.</Text>
            </Box>
          )}
          {batches.map((batch, index) => {
            const isSelected = index === selectedIndex;
            const textColor = isSelected ? 'cyan' : 'white';
            const statusColor = STATUS_COLORS[batch.status ?? ''] ?? 'white';
            const statusLabel = BATCH_STATUS_LABELS[(batch.status ?? '') as BatchStatus] ?? batch.status;
            const qty = `${batch.plannedQuantity ?? ''} ${batch.plannedQuantityUnit ?? ''}`;
            return (
              <Box key={batch.id} paddingX={1}>
                <Text color={textColor}>{isSelected ? '▶ ' : '  '}</Text>
                <Text color={textColor}>{(batch.batchNumber ?? '').substring(0, 14).padEnd(15)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{qty.substring(0, 12).padEnd(14)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{(batch.productionDate ?? '').padEnd(14)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{(batch.bestBeforeDate ?? '').padEnd(14)}</Text>
                <Text color={isSelected ? 'cyan' : statusColor}>{statusLabel}</Text>
              </Box>
            );
          })}
        </Box>
      )}

      <Box marginTop={1}>
        <Text color="gray" dimColor>
          ↑↓ nav · Enter Details · [n] Neu · [a] Alle [P] Geplant [I] In Prod. [C] Abgeschl. [X] Storniert · Backspace Zurück
        </Text>
      </Box>
    </Box>
  );
}
