import React, { useEffect, useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../state/navigation-context.js';
import { useInventoryCounts } from '../../hooks/useInventoryCounts.js';
import { useStockNameLookup } from '../../hooks/useStockNameLookup.js';
import { LoadingSpinner } from '../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../shared/ErrorDisplay.js';
import { INVENTORY_COUNT_STATUS_LABELS } from '@effigenix/api-client';
import type { InventoryCountStatus } from '@effigenix/api-client';

type StatusFilter = 'ALL' | InventoryCountStatus;
const FILTER_CYCLE: StatusFilter[] = ['ALL', 'OPEN', 'COUNTING', 'COMPLETED', 'CANCELLED'];

const STATUS_COLORS: Record<InventoryCountStatus, string> = {
  OPEN: 'yellow',
  COUNTING: 'blue',
  COMPLETED: 'green',
  CANCELLED: 'red',
};

export function InventoryCountListScreen() {
  const { navigate, back } = useNavigation();
  const { inventoryCounts, loading, error, fetchInventoryCounts, clearError } = useInventoryCounts();
  const { locationName } = useStockNameLookup();
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('ALL');

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

  const filtered = statusFilter === 'ALL'
    ? inventoryCounts
    : inventoryCounts.filter((c) => c.status === statusFilter);

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

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

    if (key.return && filtered.length > 0) {
      const item = filtered[selectedIndex];
      if (item) navigate('inventory-count-detail', { inventoryCountId: item.id });
    }
    if (input === 'n') navigate('inventory-count-create');
    if (input === 'r') void fetchInventoryCounts();
    if (input === 'f') {
      setStatusFilter((current) => {
        const idx = FILTER_CYCLE.indexOf(current);
        return FILTER_CYCLE[(idx + 1) % FILTER_CYCLE.length]!;
      });
      setSelectedIndex(0);
    }
    if (key.backspace || key.escape) back();
  });

  const filterLabel = statusFilter === 'ALL' ? 'Alle' : INVENTORY_COUNT_STATUS_LABELS[statusFilter];

  return (
    <Box flexDirection="column" gap={1}>
      <Box gap={2}>
        <Text color="cyan" bold>Inventuren</Text>
        <Text color="gray" dimColor>
          Status: <Text color="yellow">{filterLabel}</Text>
          {' '}({filtered.length})
        </Text>
      </Box>

      {loading && <LoadingSpinner label="Lade Inventuren..." />}
      {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>{'  Status'.padEnd(18)}</Text>
            <Text color="gray" bold>{'Lagerort'.padEnd(22)}</Text>
            <Text color="gray" bold>{'Datum'.padEnd(14)}</Text>
            <Text color="gray" bold>{'Fortschritt'.padEnd(14)}</Text>
            <Text color="gray" bold>Erstellt von</Text>
          </Box>
          {filtered.length === 0 && (
            <Box paddingX={1} paddingY={1}>
              <Text color="gray" dimColor>Keine Inventuren gefunden.</Text>
            </Box>
          )}
          {filtered.map((count, index) => {
            const isSelected = index === selectedIndex;
            const textColor = isSelected ? 'cyan' : 'white';
            const statusColor = STATUS_COLORS[count.status] ?? 'white';
            const statusLabel = INVENTORY_COUNT_STATUS_LABELS[count.status] ?? count.status;
            const counted = count.countItems.filter((i) => i.actualQuantityAmount !== null).length;
            const total = count.countItems.length;
            const progress = `${counted}/${total}`;
            return (
              <Box key={count.id} paddingX={1}>
                <Text color={textColor}>{isSelected ? '▶ ' : '  '}</Text>
                <Text color={statusColor}>{statusLabel.padEnd(15)}</Text>
                <Text color={textColor}>{locationName(count.storageLocationId).substring(0, 20).padEnd(21)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{count.countDate.padEnd(14)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{progress.padEnd(14)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{count.initiatedBy}</Text>
              </Box>
            );
          })}
        </Box>
      )}

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