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

const STATUS_FILTERS: { key: string; label: string; value: RecipeStatus | undefined }[] = [
  { key: 'a', label: 'ALLE', value: undefined },
  { key: 'D', label: 'DRAFT', value: 'DRAFT' },
  { key: 'A', label: 'ACTIVE', value: 'ACTIVE' },
  { key: 'R', label: 'ARCHIVED', value: 'ARCHIVED' },
];

const STATUS_COLORS: Record<string, string> = {
  DRAFT: 'yellow',
  ACTIVE: 'green',
  ARCHIVED: 'gray',
};

export function RecipeListScreen() {
  const { navigate, back } = useNavigation();
  const { recipes, loading, error, fetchRecipes, clearError } = useRecipes();
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [statusFilter, setStatusFilter] = useState<RecipeStatus | undefined>(undefined);

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

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

    if (key.upArrow) setSelectedIndex((i) => Math.max(0, i - 1));
    if (key.downArrow) setSelectedIndex((i) => Math.min(recipes.length - 1, i + 1));

    if (key.return && recipes.length > 0) {
      const recipe = recipes[selectedIndex];
      if (recipe) navigate('recipe-detail', { recipeId: recipe.id });
    }
    if (input === 'n') navigate('recipe-create');
    if (key.backspace || key.escape) back();

    // Status-Filter
    for (const filter of STATUS_FILTERS) {
      if (input === filter.key) {
        setStatusFilter(filter.value);
        setSelectedIndex(0);
        break;
      }
    }
  });

  const activeFilterLabel = STATUS_FILTERS.find((f) => f.value === statusFilter)?.label ?? 'ALLE';

  return (
    <Box flexDirection="column" gap={1}>
      <Box gap={2}>
        <Text color="cyan" bold>Rezepte</Text>
        <Text color="gray" dimColor>({recipes.length})</Text>
        <Text color="gray" dimColor>Filter: </Text>
        <Text color="yellow" bold>{activeFilterLabel}</Text>
      </Box>

      {loading && <LoadingSpinner label="Lade Rezepte..." />}
      {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>{'  Name'.padEnd(30)}</Text>
            <Text color="gray" bold>{'Typ'.padEnd(18)}</Text>
            <Text color="gray" bold>{'V.'.padEnd(5)}</Text>
            <Text color="gray" bold>Status</Text>
          </Box>
          {recipes.length === 0 && (
            <Box paddingX={1} paddingY={1}>
              <Text color="gray" dimColor>Keine Rezepte gefunden.</Text>
            </Box>
          )}
          {recipes.map((recipe, index) => {
            const isSelected = index === selectedIndex;
            const textColor = isSelected ? 'cyan' : 'white';
            const typeName = RECIPE_TYPE_LABELS[recipe.type as RecipeType] ?? recipe.type;
            const statusColor = STATUS_COLORS[recipe.status] ?? 'white';
            return (
              <Box key={recipe.id} paddingX={1}>
                <Text color={textColor}>{isSelected ? '▶ ' : '  '}</Text>
                <Text color={textColor}>{recipe.name.substring(0, 26).padEnd(27)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{typeName.padEnd(18)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{String(recipe.version).padEnd(5)}</Text>
                <Text color={isSelected ? 'cyan' : statusColor}>{recipe.status}</Text>
              </Box>
            );
          })}
        </Box>
      )}

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