import React, { useCallback, useEffect, useState } from 'react'; import { Box, Text, useInput } from 'ink'; import type { CustomerPreference } from '@effigenix/api-client'; import { CUSTOMER_PREFERENCE_LABELS } from '@effigenix/api-client'; 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 { client } from '../../../utils/api-client.js'; const ALL_PREFERENCES: CustomerPreference[] = [ 'BIO', 'REGIONAL', 'TIERWOHL', 'HALAL', 'KOSHER', 'GLUTENFREI', 'LAKTOSEFREI', ]; function errorMessage(err: unknown): string { return err instanceof Error ? err.message : 'Unbekannter Fehler'; } export function SetPreferencesScreen() { const { params, replace, back } = useNavigation(); const customerId = params['customerId'] ?? ''; const { setPreferences, loading, error, clearError } = useCustomers(); const [selectedIndex, setSelectedIndex] = useState(0); const [checked, setChecked] = useState>(new Set()); const [initLoading, setInitLoading] = useState(true); const [initError, setInitError] = useState(null); useEffect(() => { client.customers.getById(customerId) .then((c) => { setChecked(new Set(c.preferences)); setInitLoading(false); }) .catch((err: unknown) => { setInitError(errorMessage(err)); setInitLoading(false); }); }, [customerId]); useInput((_input, key) => { if (initLoading || loading) return; if (key.upArrow) setSelectedIndex((i) => Math.max(0, i - 1)); if (key.downArrow) setSelectedIndex((i) => Math.min(ALL_PREFERENCES.length - 1, i + 1)); if (_input === ' ') { const pref = ALL_PREFERENCES[selectedIndex]; if (pref) { setChecked((prev) => { const next = new Set(prev); if (next.has(pref)) next.delete(pref); else next.add(pref); return next; }); } } if (key.return) void handleSave(); if (key.escape) back(); }); const handleSave = useCallback(async () => { const updated = await setPreferences(customerId, Array.from(checked)); if (updated) replace('customer-detail', { customerId }); }, [customerId, checked, setPreferences, replace]); if (initLoading) return ; if (initError) return ; if (loading) return ; return ( Präferenzen setzen {error && } {ALL_PREFERENCES.map((pref, i) => { const isSelected = i === selectedIndex; const isChecked = checked.has(pref); return ( {isSelected ? '▶' : ' '} {isChecked ? '[✓]' : '[ ]'} {CUSTOMER_PREFERENCE_LABELS[pref]} ); })} ↑↓ navigieren · Leertaste togglen · Enter speichern · Escape Abbrechen ); }