import React, { useCallback, useEffect, useState } from 'react';
import { Box, Text, useInput } from 'ink';
import type { CustomerDTO, 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 { SuccessDisplay } from '../../shared/SuccessDisplay.js';
import { ConfirmDialog } from '../../shared/ConfirmDialog.js';
import { client } from '../../../utils/api-client.js';

type MenuAction =
  | 'toggle-status'
  | 'add-delivery-address'
  | 'remove-delivery-address'
  | 'set-preferences'
  | 'back';

type Mode = 'menu' | 'confirm-status' | 'select-remove-address';

const MENU_ITEMS: { id: MenuAction; label: (c: CustomerDTO) => string }[] = [
  { id: 'toggle-status', label: (c) => c.status === 'ACTIVE' ? '[Deaktivieren]' : '[Aktivieren]' },
  { id: 'add-delivery-address', label: () => '[Lieferadresse hinzufügen]' },
  { id: 'remove-delivery-address', label: (c) => c.deliveryAddresses.length > 0 ? '[Lieferadresse entfernen]' : '[Entfernen (keine vorhanden)]' },
  { id: 'set-preferences', label: () => '[Präferenzen setzen]' },
  { id: 'back', label: () => '[Zurück]' },
];

function errorMessage(err: unknown): string {
  return err instanceof Error ? err.message : 'Unbekannter Fehler';
}

function formatDate(d: string): string {
  return new Date(d).toLocaleDateString('de-DE');
}

export function CustomerDetailScreen() {
  const { params, navigate, back } = useNavigation();
  const customerId = params['customerId'] ?? '';
  const { activateCustomer, deactivateCustomer, removeDeliveryAddress } = useCustomers();

  const [customer, setCustomer] = useState<CustomerDTO | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedAction, setSelectedAction] = useState(0);
  const [mode, setMode] = useState<Mode>('menu');
  const [actionLoading, setActionLoading] = useState(false);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [selectedAddrIndex, setSelectedAddrIndex] = useState(0);

  const loadCustomer = useCallback(() => {
    setLoading(true);
    setError(null);
    client.customers.getById(customerId)
      .then((c) => { setCustomer(c); setLoading(false); })
      .catch((err: unknown) => { setError(errorMessage(err)); setLoading(false); });
  }, [customerId]);

  useEffect(() => { if (customerId) loadCustomer(); }, [loadCustomer, customerId]);

  useInput((_input, key) => {
    if (loading || actionLoading) return;

    if (mode === 'select-remove-address' && customer) {
      if (key.upArrow) setSelectedAddrIndex((i) => Math.max(0, i - 1));
      if (key.downArrow) setSelectedAddrIndex((i) => Math.min(customer.deliveryAddresses.length - 1, i + 1));
      if (key.return) {
        const addr = customer.deliveryAddresses[selectedAddrIndex];
        if (addr) void handleRemoveAddress(addr.label);
      }
      if (key.escape) setMode('menu');
      return;
    }

    if (mode !== 'menu') return;
    if (key.upArrow) setSelectedAction((i) => Math.max(0, i - 1));
    if (key.downArrow) setSelectedAction((i) => Math.min(MENU_ITEMS.length - 1, i + 1));
    if (key.return) void handleAction();
    if (key.backspace || key.escape) back();
  });

  const handleAction = async () => {
    if (!customer) return;
    const item = MENU_ITEMS[selectedAction];
    if (!item) return;

    switch (item.id) {
      case 'toggle-status':
        setMode('confirm-status');
        break;
      case 'add-delivery-address':
        navigate('customer-add-delivery-address', { customerId: customer.id });
        break;
      case 'remove-delivery-address':
        if (customer.deliveryAddresses.length > 0) {
          setSelectedAddrIndex(0);
          setMode('select-remove-address');
        }
        break;
      case 'set-preferences':
        navigate('customer-set-preferences', { customerId: customer.id });
        break;
      case 'back':
        back();
        break;
    }
  };

  const handleToggleStatus = useCallback(async () => {
    if (!customer) return;
    setMode('menu');
    setActionLoading(true);
    const fn = customer.status === 'ACTIVE' ? deactivateCustomer : activateCustomer;
    const updated = await fn(customer.id);
    setActionLoading(false);
    if (updated) {
      setCustomer(updated);
      setSuccessMessage(customer.status === 'ACTIVE' ? 'Kunde deaktiviert.' : 'Kunde aktiviert.');
    }
  }, [customer, activateCustomer, deactivateCustomer]);

  const handleRemoveAddress = useCallback(async (label: string) => {
    if (!customer) return;
    setMode('menu');
    setActionLoading(true);
    const updated = await removeDeliveryAddress(customer.id, label);
    setActionLoading(false);
    if (updated) {
      setCustomer(updated);
      setSuccessMessage(`Lieferadresse "${label}" entfernt.`);
    }
  }, [customer, removeDeliveryAddress]);

  if (loading) return <LoadingSpinner label="Lade Kunde..." />;
  if (error && !customer) return <ErrorDisplay message={error} onDismiss={back} />;
  if (!customer) return <Text color="red">Kunde nicht gefunden.</Text>;

  const statusColor = customer.status === 'ACTIVE' ? 'green' : 'red';
  const ba = customer.billingAddress;
  const billingText = ba ? `${ba.street} ${ba.houseNumber}, ${ba.postalCode} ${ba.city}, ${ba.country}` : '–';

  return (
    <Box flexDirection="column" gap={1}>
      <Text color="cyan" bold>Kunde: {customer.name}</Text>

      {error && <ErrorDisplay message={error} onDismiss={() => setError(null)} />}
      {successMessage && <SuccessDisplay message={successMessage} onDismiss={() => setSuccessMessage(null)} />}

      {/* Info-Box */}
      <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={2} paddingY={1}>
        <Box gap={2}>
          <Text color="gray">Status:</Text>
          <Text color={statusColor} bold>{customer.status}</Text>
          <Text color="yellow">{customer.type}</Text>
        </Box>
        <Box gap={2}>
          <Text color="gray">Telefon:</Text>
          <Text>{customer.contactInfo.phone}</Text>
        </Box>
        {customer.contactInfo.email && (
          <Box gap={2}>
            <Text color="gray">E-Mail:</Text>
            <Text>{customer.contactInfo.email}</Text>
          </Box>
        )}
        <Box gap={2}>
          <Text color="gray">Rechnungsadresse:</Text>
          <Text>{billingText}</Text>
        </Box>
        {customer.paymentTerms && (
          <Box gap={2}>
            <Text color="gray">Zahlungsziel:</Text>
            <Text>{customer.paymentTerms.paymentDueDays} Tage</Text>
          </Box>
        )}
        {customer.preferences.length > 0 && (
          <Box gap={2}>
            <Text color="gray">Präferenzen:</Text>
            <Text>{customer.preferences.map((p) => CUSTOMER_PREFERENCE_LABELS[p as CustomerPreference]).join(', ')}</Text>
          </Box>
        )}
        {customer.deliveryAddresses.length > 0 && (
          <Box flexDirection="column" marginTop={1}>
            <Text color="gray">Lieferadressen ({customer.deliveryAddresses.length}):</Text>
            {customer.deliveryAddresses.map((addr) => (
              <Box key={addr.label} paddingLeft={2} gap={1}>
                <Text color="yellow">•</Text>
                <Text bold>{addr.label}:</Text>
                <Text>{addr.address ? `${addr.address.street} ${addr.address.houseNumber}, ${addr.address.city}, ${addr.address.country}` : '–'}</Text>
              </Box>
            ))}
          </Box>
        )}
        {customer.frameContract && (
          <Box flexDirection="column" marginTop={1}>
            <Text color="gray">Rahmenvertrag:</Text>
            <Box paddingLeft={2} gap={1}>
              <Text>{customer.frameContract.validFrom ? formatDate(customer.frameContract.validFrom) : '–'} – {customer.frameContract.validUntil ? formatDate(customer.frameContract.validUntil) : '–'}</Text>
              <Text color="gray">({customer.frameContract.lineItems.length} Positionen)</Text>
            </Box>
          </Box>
        )}
      </Box>

      {/* Confirm Status */}
      {mode === 'confirm-status' && (
        <ConfirmDialog
          message={customer.status === 'ACTIVE' ? 'Kunde deaktivieren?' : 'Kunde aktivieren?'}
          onConfirm={() => void handleToggleStatus()}
          onCancel={() => setMode('menu')}
        />
      )}

      {/* Select Address to Remove */}
      {mode === 'select-remove-address' && (
        <Box flexDirection="column" gap={1}>
          <Text color="yellow">Lieferadresse entfernen:</Text>
          {customer.deliveryAddresses.map((addr, i) => (
            <Box key={addr.label}>
              <Text color={i === selectedAddrIndex ? 'cyan' : 'white'}>
                {i === selectedAddrIndex ? '▶ ' : '  '}{addr.label}: {addr.address?.city ?? '–'}
              </Text>
            </Box>
          ))}
          <Text color="gray" dimColor>↑↓ auswählen · Enter Entfernen · Escape Abbrechen</Text>
        </Box>
      )}

      {/* Action Menu */}
      {mode === 'menu' && (
        <Box flexDirection="column">
          <Text color="gray" bold>Aktionen:</Text>
          {actionLoading && <LoadingSpinner label="Aktion wird ausgeführt..." />}
          {!actionLoading && MENU_ITEMS.map((item, index) => (
            <Box key={item.id}>
              <Text color={index === selectedAction ? 'cyan' : 'white'}>
                {index === selectedAction ? '▶ ' : '  '}{item.label(customer)}
              </Text>
            </Box>
          ))}
        </Box>
      )}

      <Box marginTop={1}>
        <Text color="gray" dimColor>↑↓ navigieren · Enter ausführen · Backspace Zurück</Text>
      </Box>
    </Box>
  );
}
