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

type Filter = 'ALL' | 'ACTIVE' | 'INACTIVE';

const STORAGE_TYPES: StorageType[] = ['COLD_ROOM', 'FREEZER', 'DRY_STORAGE', 'DISPLAY_COUNTER', 'PRODUCTION_AREA'];

export function StorageLocationListScreen() {
  const { navigate, back } = useNavigation();
  const { storageLocations, loading, error, fetchStorageLocations, clearError } = useStorageLocations();
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [statusFilter, setStatusFilter] = useState<Filter>('ALL');
  const [typeFilter, setTypeFilter] = useState<StorageType | null>(null);

  useEffect(() => {
    const filter: StorageLocationFilter = {};
    if (typeFilter) filter.storageType = typeFilter;
    if (statusFilter !== 'ALL') filter.active = statusFilter === 'ACTIVE';
    void fetchStorageLocations(filter);
  }, [fetchStorageLocations, statusFilter, typeFilter]);

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

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

    if (key.return && storageLocations.length > 0) {
      const loc = storageLocations[selectedIndex];
      if (loc) navigate('storage-location-detail', { storageLocationId: loc.id });
    }
    if (input === 'n') navigate('storage-location-create');
    if (input === 'a') { setStatusFilter('ALL'); setSelectedIndex(0); }
    if (input === 'A') { setStatusFilter('ACTIVE'); setSelectedIndex(0); }
    if (input === 'I') { setStatusFilter('INACTIVE'); setSelectedIndex(0); }
    if (input === 't') {
      setTypeFilter((current) => {
        if (!current) return STORAGE_TYPES[0] ?? null;
        const idx = STORAGE_TYPES.indexOf(current);
        if (idx >= STORAGE_TYPES.length - 1) return null;
        return STORAGE_TYPES[idx + 1] ?? null;
      });
      setSelectedIndex(0);
    }
    if (key.backspace || key.escape) back();
  });

  const filterLabel: Record<Filter, string> = { ALL: 'Alle', ACTIVE: 'Aktiv', INACTIVE: 'Inaktiv' };
  const typeLabel = typeFilter ? STORAGE_TYPE_LABELS[typeFilter] : 'Alle';

  return (
    <Box flexDirection="column" gap={1}>
      <Box gap={2}>
        <Text color="cyan" bold>Lagerorte</Text>
        <Text color="gray" dimColor>
          Status: <Text color="yellow">{filterLabel[statusFilter]}</Text>
          {' · '}Typ: <Text color="yellow">{typeLabel}</Text>
          {' '}({storageLocations.length})
        </Text>
      </Box>

      {loading && <LoadingSpinner label="Lade Lagerorte..." />}
      {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(30)}</Text>
            <Text color="gray" bold>{'Typ'.padEnd(20)}</Text>
            <Text color="gray" bold>Temperatur</Text>
          </Box>
          {storageLocations.length === 0 && (
            <Box paddingX={1} paddingY={1}>
              <Text color="gray" dimColor>Keine Lagerorte gefunden.</Text>
            </Box>
          )}
          {storageLocations.map((loc, index) => {
            const isSelected = index === selectedIndex;
            const statusColor = loc.active ? 'green' : 'red';
            const textColor = isSelected ? 'cyan' : 'white';
            const typeName = STORAGE_TYPE_LABELS[loc.storageType as StorageType] ?? loc.storageType;
            const tempRange = loc.temperatureRange
              ? `${loc.temperatureRange.minTemperature}°C – ${loc.temperatureRange.maxTemperature}°C`
              : '–';
            return (
              <Box key={loc.id} paddingX={1}>
                <Text color={textColor}>{isSelected ? '▶ ' : '  '}</Text>
                <Text color={statusColor}>{loc.active ? '● ' : '○ '}</Text>
                <Text color={textColor}>{loc.name.substring(0, 24).padEnd(25)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{typeName.padEnd(20)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{tempRange}</Text>
              </Box>
            );
          })}
        </Box>
      )}

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