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

type StatusFilter = 'ALL' | CustomerStatus;
type TypeFilter = 'ALL' | CustomerType;

export function CustomerListScreen() {
  const { navigate, back } = useNavigation();
  const { customers, loading, error, fetchCustomers, clearError } = useCustomers();
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('ALL');
  const [typeFilter, setTypeFilter] = useState<TypeFilter>('ALL');

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

  const filtered = customers.filter(
    (c) =>
      (statusFilter === 'ALL' || c.status === statusFilter) &&
      (typeFilter === 'ALL' || c.type === typeFilter),
  );

  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 cust = filtered[selectedIndex];
      if (cust) navigate('customer-detail', { customerId: cust.id });
    }
    if (input === 'n') navigate('customer-create');
    if (input === 'a') { setStatusFilter('ALL'); setSelectedIndex(0); }
    if (input === 'A') { setStatusFilter('ACTIVE'); setSelectedIndex(0); }
    if (input === 'I') { setStatusFilter('INACTIVE'); setSelectedIndex(0); }
    if (input === 'b') { setTypeFilter('ALL'); setSelectedIndex(0); }
    if (input === 'B') { setTypeFilter('B2B'); setSelectedIndex(0); }
    if (input === 'C') { setTypeFilter('B2C'); setSelectedIndex(0); }
    if (key.backspace || key.escape) back();
  });

  return (
    <Box flexDirection="column" gap={1}>
      <Box gap={2}>
        <Text color="cyan" bold>Kunden</Text>
        <Text color="gray" dimColor>
          Status: <Text color="yellow">{statusFilter}</Text>
          {'  '}Typ: <Text color="yellow">{typeFilter}</Text>
          {'  '}({filtered.length})
        </Text>
      </Box>

      {loading && <LoadingSpinner label="Lade Kunden..." />}
      {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 Typ  Name'.padEnd(34)}</Text>
            <Text color="gray" bold>Adr.</Text>
          </Box>
          {filtered.length === 0 && (
            <Box paddingX={1} paddingY={1}>
              <Text color="gray" dimColor>Keine Kunden gefunden.</Text>
            </Box>
          )}
          {filtered.map((cust, index) => {
            const isSelected = index === selectedIndex;
            const statusColor = cust.status === 'ACTIVE' ? 'green' : 'red';
            const textColor = isSelected ? 'cyan' : 'white';
            return (
              <Box key={cust.id} paddingX={1}>
                <Text color={textColor}>{isSelected ? '▶ ' : '  '}</Text>
                <Text color={statusColor}>{cust.status === 'ACTIVE' ? '● ' : '○ '}</Text>
                <Text color="yellow">{cust.type.padEnd(4)} </Text>
                <Text color={textColor}>{cust.name.substring(0, 26).padEnd(27)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{cust.deliveryAddresses.length} Adr.</Text>
              </Box>
            );
          })}
        </Box>
      )}

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