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

type Filter = 'ALL' | ArticleStatus;

export function ArticleListScreen() {
  const { navigate, back } = useNavigation();
  const { articles, loading, error, fetchArticles, clearError } = useArticles();
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [filter, setFilter] = useState<Filter>('ALL');

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

  const filtered = filter === 'ALL' ? articles : articles.filter((a) => a.status === filter);

  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 art = filtered[selectedIndex];
      if (art) navigate('article-detail', { articleId: art.id });
    }
    if (input === 'n') navigate('article-create');
    if (input === 'a') { setFilter('ALL'); setSelectedIndex(0); }
    if (input === 'A') { setFilter('ACTIVE'); setSelectedIndex(0); }
    if (input === 'I') { setFilter('INACTIVE'); setSelectedIndex(0); }
    if (key.backspace || key.escape) back();
  });

  const filterLabel: Record<Filter, string> = { ALL: 'Alle', ACTIVE: 'Aktiv', INACTIVE: 'Inaktiv' };

  return (
    <Box flexDirection="column" gap={1}>
      <Box gap={2}>
        <Text color="cyan" bold>Artikel</Text>
        <Text color="gray" dimColor>Filter: <Text color="yellow">{filterLabel[filter]}</Text> ({filtered.length})</Text>
      </Box>

      {loading && <LoadingSpinner label="Lade Artikel..." />}
      {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>{'  St Nummer     Name'.padEnd(38)}</Text>
            <Text color="gray" bold>Einh.</Text>
          </Box>
          {filtered.length === 0 && (
            <Box paddingX={1} paddingY={1}>
              <Text color="gray" dimColor>Keine Artikel gefunden.</Text>
            </Box>
          )}
          {filtered.map((art, index) => {
            const isSelected = index === selectedIndex;
            const statusColor = art.status === 'ACTIVE' ? 'green' : 'red';
            const textColor = isSelected ? 'cyan' : 'white';
            return (
              <Box key={art.id} paddingX={1}>
                <Text color={textColor}>{isSelected ? '▶ ' : '  '}</Text>
                <Text color={statusColor}>{art.status === 'ACTIVE' ? '● ' : '○ '}</Text>
                <Text color={textColor}>{art.articleNumber.padEnd(10)}</Text>
                <Text color={textColor}>{art.name.substring(0, 22).padEnd(23)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{art.salesUnits.length} VE</Text>
              </Box>
            );
          })}
        </Box>
      )}

      <Box marginTop={1}>
        <Text color="gray" dimColor>
          ↑↓ nav · Enter Details · [n] Neu · [a] Alle · [A] Aktiv · [I] Inaktiv · Backspace Zurück
        </Text>
      </Box>
    </Box>
  );
}
