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

type Filter = 'ALL' | SupplierStatus;

function avgRating(rating: { qualityScore: number; deliveryScore: number; priceScore: number } | null | undefined): string {
  if (!rating) return '–';
  const avg = (rating.qualityScore + rating.deliveryScore + rating.priceScore) / 3;
  return avg.toFixed(1);
}

export function SupplierListScreen() {
  const { navigate, back } = useNavigation();
  const { suppliers, loading, error, fetchSuppliers, clearError } = useSuppliers();
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [filter, setFilter] = useState<Filter>('ALL');

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

  const filtered = filter === 'ALL' ? suppliers : suppliers.filter((s) => s.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 sup = filtered[selectedIndex];
      if (sup) navigate('supplier-detail', { supplierId: sup.id });
    }
    if (input === 'n') navigate('supplier-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>Lieferanten</Text>
        <Text color="gray" dimColor>Filter: <Text color="yellow">{filterLabel[filter]}</Text> ({filtered.length})</Text>
      </Box>

      {loading && <LoadingSpinner label="Lade Lieferanten..." />}
      {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>{'  Status  Name'.padEnd(32)}</Text>
            <Text color="gray" bold>{'Bewertung  Zertifikate'}</Text>
          </Box>
          {filtered.length === 0 && (
            <Box paddingX={1} paddingY={1}>
              <Text color="gray" dimColor>Keine Lieferanten gefunden.</Text>
            </Box>
          )}
          {filtered.map((sup, index) => {
            const isSelected = index === selectedIndex;
            const statusColor = sup.status === 'ACTIVE' ? 'green' : 'red';
            const textColor = isSelected ? 'cyan' : 'white';
            return (
              <Box key={sup.id} paddingX={1}>
                <Text color={textColor}>{isSelected ? '▶ ' : '  '}</Text>
                <Text color={statusColor}>{(sup.status === 'ACTIVE' ? '● ' : '○ ')}</Text>
                <Text color={textColor}>{sup.name.substring(0, 26).padEnd(27)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{`★ ${avgRating(sup.rating)}  `}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{`${sup.certificates.length} Zert.`}</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>
  );
}
