import { useState, useMemo } from 'react';
import { Box, Text, useInput } from 'ink';
import type { StockDTO } from '@effigenix/api-client';

interface StockPickerProps {
  stocks: StockDTO[];
  query: string;
  onQueryChange: (q: string) => void;
  onSelect: (stock: StockDTO) => void;
  focus: boolean;
  selectedLabel?: string | undefined;
  maxVisible?: number;
  articleName: (id: string) => string;
  locationName: (id: string) => string;
}

export function StockPicker({
  stocks,
  query,
  onQueryChange,
  onSelect,
  focus,
  selectedLabel,
  maxVisible = 5,
  articleName,
  locationName,
}: StockPickerProps) {
  const [cursor, setCursor] = useState(0);

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

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

    if (key.upArrow) {
      setCursor((c) => Math.max(0, c - 1));
      return;
    }
    if (key.downArrow) {
      setCursor((c) => Math.min(filtered.length - 1, c + 1));
      return;
    }
    if (key.return && filtered.length > 0) {
      const selected = filtered[cursor];
      if (selected) onSelect(selected);
      return;
    }
    if (key.backspace || key.delete) {
      onQueryChange(query.slice(0, -1));
      setCursor(0);
      return;
    }

    if (key.tab || key.escape || key.ctrl || key.meta) return;

    if (input && !key.upArrow && !key.downArrow) {
      onQueryChange(query + input);
      setCursor(0);
    }
  }, { isActive: focus });

  if (!focus && selectedLabel) {
    return (
      <Box flexDirection="column">
        <Text color="gray">Bestand *</Text>
        <Box>
          <Text color="gray"> › </Text>
          <Text color="green">✓ {selectedLabel}</Text>
        </Box>
      </Box>
    );
  }

  if (focus && selectedLabel && !query) {
    return (
      <Box flexDirection="column">
        <Text color="cyan">Bestand * (tippen zum Ändern)</Text>
        <Box>
          <Text color="gray"> › </Text>
          <Text color="green">✓ {selectedLabel}</Text>
        </Box>
      </Box>
    );
  }

  return (
    <Box flexDirection="column">
      <Text color={focus ? 'cyan' : 'gray'}>Bestand * (Suche)</Text>
      <Box>
        <Text color="gray"> › </Text>
        <Text>{query || (focus ? '▌' : '')}</Text>
      </Box>
      {focus && filtered.length > 0 && (
        <Box flexDirection="column" paddingLeft={2}>
          {filtered.map((s, i) => {
            const availStr = `${s.availableQuantity}${s.quantityUnit ? ` ${s.quantityUnit}` : ''}`;
            return (
              <Box key={s.id}>
                <Text color={i === cursor ? 'cyan' : 'white'}>
                  {i === cursor ? '▶ ' : '  '}{articleName(s.articleId)} | {locationName(s.storageLocationId)} | {availStr}
                </Text>
              </Box>
            );
          })}
        </Box>
      )}
      {focus && query && filtered.length === 0 && (
        <Box paddingLeft={2}>
          <Text color="yellow">Keine Bestände gefunden.</Text>
        </Box>
      )}
    </Box>
  );
}
