import { useState, useEffect } 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 { StockPicker } from '../shared/StockPicker.js';
import { LoadingSpinner } from '../shared/LoadingSpinner.js';

export function StockBatchEntryScreen() {
  const { navigate, back } = useNavigation();
  const { stocks, loading, fetchStocks } = useStocks();
  const { articleName, locationName } = useStockNameLookup();
  const [query, setQuery] = useState('');
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [selectedLabel, setSelectedLabel] = useState<string | undefined>(undefined);

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

  useInput((_input, key) => {
    if (key.escape) back();
  });

  return (
    <Box flexDirection="column" gap={1}>
      <Text color="cyan" bold>Charge einbuchen</Text>
      <Text color="gray">Suchen Sie den Bestand, um eine neue Charge einzubuchen.</Text>

      {loading && <LoadingSpinner label="Lade Bestände..." />}

      {!loading && (
        <Box flexDirection="column" width={80}>
          <StockPicker
            stocks={stocks}
            query={query}
            onQueryChange={(q) => {
              setQuery(q);
              setSelectedId(null);
              setSelectedLabel(undefined);
            }}
            onSelect={(stock) => {
              setSelectedId(stock.id);
              setSelectedLabel(`${articleName(stock.articleId)} | ${locationName(stock.storageLocationId)}`);
              setQuery('');
              navigate('stock-add-batch', { stockId: stock.id });
            }}
            focus={!selectedId}
            selectedLabel={selectedLabel}
            articleName={articleName}
            locationName={locationName}
          />
        </Box>
      )}

      <Box marginTop={1}>
        <Text color="gray" dimColor>
          ↑↓ nav · Enter Auswählen · Escape Zurück
        </Text>
      </Box>
    </Box>
  );
}
