import React, { useEffect, useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../../state/navigation-context.js';
import { useCategories } from '../../../hooks/useCategories.js';
import { LoadingSpinner } from '../../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../../shared/ErrorDisplay.js';
import { ConfirmDialog } from '../../shared/ConfirmDialog.js';
import { SuccessDisplay } from '../../shared/SuccessDisplay.js';

export function CategoryListScreen() {
  const { navigate, back } = useNavigation();
  const { categories, loading, error, fetchCategories, deleteCategory, clearError } = useCategories();
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

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

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

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

    if (key.return && categories.length > 0) {
      const cat = categories[selectedIndex];
      if (cat) navigate('category-detail', { categoryId: cat.id });
    }
    if (input === 'n') navigate('category-create');
    if (input === 'd' && categories.length > 0) {
      const cat = categories[selectedIndex];
      if (cat) setConfirmDeleteId(cat.id);
    }
    if (key.backspace || key.escape) back();
  });

  const handleDelete = async () => {
    if (!confirmDeleteId) return;
    const cat = categories.find((c) => c.id === confirmDeleteId);
    const ok = await deleteCategory(confirmDeleteId);
    setConfirmDeleteId(null);
    if (ok) {
      setSuccessMessage(`Kategorie "${cat?.name ?? ''}" gelöscht.`);
      setSelectedIndex((i) => Math.max(0, i - 1));
    }
  };

  return (
    <Box flexDirection="column" gap={1}>
      <Box>
        <Text color="cyan" bold>Produktkategorien</Text>
        <Text color="gray" dimColor> – {categories.length} Einträge</Text>
      </Box>

      {loading && <LoadingSpinner label="Lade Kategorien..." />}
      {error && !loading && <ErrorDisplay message={error} onDismiss={clearError} />}
      {successMessage && <SuccessDisplay message={successMessage} onDismiss={() => setSuccessMessage(null)} />}

      {confirmDeleteId && (
        <ConfirmDialog
          message={`Kategorie "${categories.find((c) => c.id === confirmDeleteId)?.name}" löschen?`}
          onConfirm={() => void handleDelete()}
          onCancel={() => setConfirmDeleteId(null)}
        />
      )}

      {!loading && !error && (
        <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={1} paddingY={0}>
          <Box borderStyle="single" borderBottom borderTop={false} borderLeft={false} borderRight={false} borderColor="gray" paddingX={1}>
            <Text color="gray" bold>{' Name'.padEnd(30)}</Text>
            <Text color="gray" bold>Beschreibung</Text>
          </Box>
          {categories.length === 0 && (
            <Box paddingX={1} paddingY={1}>
              <Text color="gray" dimColor>Keine Kategorien vorhanden.</Text>
            </Box>
          )}
          {categories.map((cat, index) => (
            <Box key={cat.id} paddingX={1}>
              <Text color={index === selectedIndex ? 'cyan' : 'white'}>
                {index === selectedIndex ? '▶ ' : '  '}
                {cat.name.padEnd(28)}
              </Text>
              <Text color={index === selectedIndex ? 'cyan' : 'gray'}>
                {cat.description ?? '–'}
              </Text>
            </Box>
          ))}
        </Box>
      )}

      <Box marginTop={1}>
        <Text color="gray" dimColor>
          ↑↓ navigieren · Enter Details · [n] Neu · [d] Löschen · Backspace Zurück
        </Text>
      </Box>
    </Box>
  );
}
