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

interface ArticlePickerProps {
  articles: ArticleDTO[];
  query: string;
  onQueryChange: (q: string) => void;
  onSelect: (article: ArticleDTO) => void;
  focus: boolean;
  selectedName?: string;
  maxVisible?: number;
}

export function ArticlePicker({
  articles,
  query,
  onQueryChange,
  onSelect,
  focus,
  selectedName,
  maxVisible = 5,
}: ArticlePickerProps) {
  const [cursor, setCursor] = useState(0);

  const filtered = useMemo(() => {
    if (!query) return [];
    const q = query.toLowerCase();
    return articles.filter(
      (a) => a.name.toLowerCase().includes(q) || a.articleNumber.toLowerCase().includes(q),
    ).slice(0, maxVisible);
  }, [articles, query, maxVisible]);

  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 && selectedName) {
    return (
      <Box flexDirection="column">
        <Text color="gray">Artikel *</Text>
        <Box>
          <Text color="gray"> › </Text>
          <Text color="green">✓ {selectedName}</Text>
        </Box>
      </Box>
    );
  }

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

  return (
    <Box flexDirection="column">
      <Text color={focus ? 'cyan' : 'gray'}>Artikel * (Suche)</Text>
      <Box>
        <Text color="gray"> › </Text>
        <Text>{query || (focus ? '▌' : '')}</Text>
      </Box>
      {focus && filtered.length > 0 && (
        <Box flexDirection="column" paddingLeft={2}>
          {filtered.map((a, i) => (
            <Box key={a.id}>
              <Text color={i === cursor ? 'cyan' : 'white'}>
                {i === cursor ? '▶ ' : '  '}{a.articleNumber} – {a.name}
              </Text>
            </Box>
          ))}
        </Box>
      )}
      {focus && query && filtered.length === 0 && (
        <Box paddingLeft={2}>
          <Text color="yellow">Keine Artikel gefunden.</Text>
        </Box>
      )}
    </Box>
  );
}
