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

const DIRECTION_COLORS: Record<string, string> = {
  IN: 'green',
  OUT: 'red',
};

export function StockMovementDetailScreen() {
  const { params, back } = useNavigation();
  const { movement, loading, error, fetchMovement, clearError } = useStockMovements();

  const [storageLabel, setStorageLabel] = useState<string | null>(null);
  const [articleLabel, setArticleLabel] = useState<string | null>(null);
  const [userLabel, setUserLabel] = useState<string | null>(null);

  const movementId = params.movementId ?? '';

  useEffect(() => {
    if (movementId) void fetchMovement(movementId);
  }, [fetchMovement, movementId]);

  // Resolve Storage Location via Stock → StorageLocation
  useEffect(() => {
    if (!movement?.stockId) return;
    void (async () => {
      try {
        const stock = await client.stocks.getById(movement.stockId);
        const loc = await client.storageLocations.getById(stock.storageLocationId);
        const typeLabel = STORAGE_TYPE_LABELS[loc.storageType as StorageType] ?? loc.storageType;
        setStorageLabel(`${loc.name} (${typeLabel})`);
      } catch { setStorageLabel(null); }
    })();
  }, [movement?.stockId]);

  // Resolve Article name + number
  useEffect(() => {
    if (!movement?.articleId) return;
    void (async () => {
      try {
        const article = await client.articles.getById(movement.articleId);
        setArticleLabel(`${article.name} (${article.articleNumber})`);
      } catch { setArticleLabel(null); }
    })();
  }, [movement?.articleId]);

  // Resolve User
  useEffect(() => {
    if (!movement?.performedBy) return;
    void (async () => {
      try {
        const user = await client.users.getById(movement.performedBy);
        setUserLabel(user.username);
      } catch { setUserLabel(null); }
    })();
  }, [movement?.performedBy]);

  useInput((_input, key) => {
    if (key.backspace || key.escape) back();
  });

  if (loading && !movement) return <LoadingSpinner label="Lade Bewegung..." />;

  if (!movement) {
    return (
      <Box flexDirection="column">
        {error && <ErrorDisplay message={error} onDismiss={clearError} />}
        <Text color="red">Bewegung nicht gefunden.</Text>
      </Box>
    );
  }

  const typeLabel = MOVEMENT_TYPE_LABELS[movement.movementType as MovementType] ?? movement.movementType;
  const dirLabel = MOVEMENT_DIRECTION_LABELS[movement.direction as MovementDirection] ?? movement.direction;
  const dirColor = DIRECTION_COLORS[movement.direction] ?? 'white';
  const dateStr = movement.performedAt
    ? new Date(movement.performedAt).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'medium' })
    : '';

  return (
    <Box flexDirection="column" gap={1}>
      <Box gap={2}>
        <Text color="cyan" bold>Bestandsbewegung</Text>
        {loading && <Text color="gray"> (aktualisiere...)</Text>}
      </Box>

      {error && <ErrorDisplay message={error} onDismiss={clearError} />}

      <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={1}>
        <Box><Text color="gray">ID:              </Text><Text>{movement.id}</Text></Box>
        <Box><Text color="gray">Typ:             </Text><Text>{typeLabel}</Text></Box>
        <Box><Text color="gray">Richtung:        </Text><Text color={dirColor}>{dirLabel}</Text></Box>
        <Box><Text color="gray">Menge:           </Text><Text>{movement.quantityAmount} {movement.quantityUnit}</Text></Box>
        <Box><Text color="gray">Lagerort:        </Text><Text>{storageLabel ?? '...'}</Text><Text dimColor> {movement.stockId}</Text></Box>
        <Box><Text color="gray">Artikel:         </Text><Text>{articleLabel ?? '...'}</Text><Text dimColor> {movement.articleId}</Text></Box>
        <Box><Text color="gray">Chargen-Nr.:     </Text><Text>{movement.batchId}</Text></Box>
        <Box><Text color="gray">Chargen-Typ:     </Text><Text>{movement.batchType}</Text></Box>
        {movement.reason && (
          <Box><Text color="gray">Grund:           </Text><Text>{movement.reason}</Text></Box>
        )}
        {movement.referenceDocumentId && (
          <Box><Text color="gray">Referenz-Dok.:   </Text><Text>{movement.referenceDocumentId}</Text></Box>
        )}
        <Box><Text color="gray">Durchgeführt von:</Text><Text> {userLabel ?? '...'}</Text><Text dimColor> {movement.performedBy}</Text></Box>
        <Box><Text color="gray">Zeitpunkt:       </Text><Text>{dateStr}</Text></Box>
      </Box>

      <Box marginTop={1}>
        <Text color="gray" dimColor>Backspace Zurück</Text>
      </Box>
    </Box>
  );
}
