import React, { useEffect, useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../state/navigation-context.js';
import { useStocks } from '../../hooks/useStocks.js';
import { useStockNameLookup } from '../../hooks/useStockNameLookup.js';
import { LoadingSpinner } from '../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../shared/ErrorDisplay.js';

export function StockListScreen() {
  const { navigate, back } = useNavigation();
  const { stocks, loading, error, fetchStocks, clearError } = useStocks();
  const { articleName, locationName } = useStockNameLookup();
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [searchMode, setSearchMode] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

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

  const filtered = React.useMemo(() => {
    if (!searchQuery) return stocks;
    const q = searchQuery.toLowerCase();
    return stocks.filter(
      (s) =>
        articleName(s.articleId).toLowerCase().includes(q) ||
        locationName(s.storageLocationId).toLowerCase().includes(q) ||
        s.articleId.toLowerCase().includes(q) ||
        s.storageLocationId.toLowerCase().includes(q),
    );
  }, [stocks, searchQuery, articleName, locationName]);

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

    if (searchMode) {
      if (key.escape) {
        setSearchMode(false);
        setSearchQuery('');
        setSelectedIndex(0);
        return;
      }
      if (key.return && filtered.length > 0) {
        const stock = filtered[selectedIndex];
        if (stock) navigate('stock-detail', { stockId: stock.id });
        return;
      }
      if (key.upArrow) {
        setSelectedIndex((i) => Math.max(0, i - 1));
        return;
      }
      if (key.downArrow) {
        setSelectedIndex((i) => Math.min(filtered.length - 1, i + 1));
        return;
      }
      if (key.backspace || key.delete) {
        setSearchQuery((q) => q.slice(0, -1));
        setSelectedIndex(0);
        return;
      }
      if (key.tab || key.ctrl || key.meta) return;
      if (input && !key.upArrow && !key.downArrow) {
        setSearchQuery((q) => q + input);
        setSelectedIndex(0);
      }
      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 stock = filtered[selectedIndex];
      if (stock) navigate('stock-detail', { stockId: stock.id });
    }
    if (input === 'n') navigate('stock-create');
    if (input === 'r') void fetchStocks();
    if (input === 's' || input === '/') {
      setSearchMode(true);
      setSelectedIndex(0);
    }
    if (key.backspace || key.escape) back();
  });

  return (
    <Box flexDirection="column" gap={1}>
      <Box gap={2}>
        <Text color="cyan" bold>Bestände</Text>
        <Text color="gray" dimColor>({filtered.length}{searchQuery ? ` / ${stocks.length}` : ''})</Text>
      </Box>

      {searchMode && (
        <Box>
          <Text color="cyan">Suche: </Text>
          <Text>{searchQuery || '▌'}</Text>
          <Text color="gray" dimColor>  (Escape zum Beenden)</Text>
        </Box>
      )}

      {loading && <LoadingSpinner label="Lade Bestände..." />}
      {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>{'  Artikel'.padEnd(24)}</Text>
            <Text color="gray" bold>{'Lagerort'.padEnd(22)}</Text>
            <Text color="gray" bold>{'Gesamt'.padEnd(14)}</Text>
            <Text color="gray" bold>{'Verfügbar'.padEnd(14)}</Text>
            <Text color="gray" bold>Chargen</Text>
          </Box>
          {filtered.length === 0 && (
            <Box paddingX={1} paddingY={1}>
              <Text color="gray" dimColor>{searchQuery ? 'Keine Treffer.' : 'Keine Bestände gefunden.'}</Text>
            </Box>
          )}
          {filtered.map((stock, index) => {
            const isSelected = index === selectedIndex;
            const textColor = isSelected ? 'cyan' : 'white';
            const totalStr = `${stock.totalQuantity}${stock.quantityUnit ? ` ${stock.quantityUnit}` : ''}`;
            const availStr = `${stock.availableQuantity}${stock.quantityUnit ? ` ${stock.quantityUnit}` : ''}`;
            const batchCount = stock.batches?.length ?? 0;
            return (
              <Box key={stock.id} paddingX={1}>
                <Text color={textColor}>{isSelected ? '▶ ' : '  '}</Text>
                <Text color={textColor}>{articleName(stock.articleId).substring(0, 20).padEnd(21)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{locationName(stock.storageLocationId).substring(0, 20).padEnd(22)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{totalStr.substring(0, 12).padEnd(14)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{availStr.substring(0, 12).padEnd(14)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{String(batchCount)}</Text>
              </Box>
            );
          })}
        </Box>
      )}

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