import React, { useEffect, useState } from 'react';
import { Box, Text, useInput } from 'ink';
import TextInput from 'ink-text-input';
import { useNavigation } from '../../state/navigation-context.js';
import { useStocks } from '../../hooks/useStocks.js';
import { useStockNameLookup } from '../../hooks/useStockNameLookup.js';
import { LoadingSpinner } from '../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../shared/ErrorDisplay.js';
import { SuccessDisplay } from '../shared/SuccessDisplay.js';
import { STOCK_BATCH_STATUS_LABELS, REFERENCE_TYPE_LABELS, RESERVATION_PRIORITY_LABELS } from '@effigenix/api-client';
import type { StockBatchStatus, ReferenceType, ReservationPriority, ReservationDTO, StockBatchDTO } from '@effigenix/api-client';

type Mode = 'view' | 'menu' | 'batch-actions' | 'block-reason' | 'remove-amount' | 'remove-unit' | 'reservation-actions' | 'confirm-release-reservation' | 'confirm-reservation-actions' | 'confirm-confirm-reservation';

const BATCH_STATUS_COLORS: Record<string, string> = {
  AVAILABLE: 'green',
  EXPIRING_SOON: 'yellow',
  EXPIRED: 'red',
  BLOCKED: 'magenta',
};

export function StockDetailScreen() {
  const { params, back, navigate } = useNavigation();
  const { stock, loading, error, fetchStock, blockBatch, unblockBatch, removeBatch, releaseReservation, confirmReservation, clearError } = useStocks();
  const { articleName, locationName } = useStockNameLookup();
  const [mode, setMode] = useState<Mode>('view');
  const [menuIndex, setMenuIndex] = useState(0);
  const [batchIndex, setBatchIndex] = useState(0);
  const [batchActionIndex, setBatchActionIndex] = useState(0);
  const [blockReason, setBlockReason] = useState('');
  const [removeAmount, setRemoveAmount] = useState('');
  const [removeUnit, setRemoveUnit] = useState('');
  const [reservationIndex, setReservationIndex] = useState(0);
  const [confirmResIndex, setConfirmResIndex] = useState(0);
  const [success, setSuccess] = useState<string | null>(null);

  const stockId = params.stockId ?? '';

  useEffect(() => {
    if (stockId) void fetchStock(stockId);
  }, [fetchStock, stockId]);

  const batches: StockBatchDTO[] = stock?.batches ?? [];
  const selectedBatch = batches[batchIndex];
  const reservations: ReservationDTO[] = (stock as { reservations?: ReservationDTO[] })?.reservations ?? [];
  const selectedReservation = reservations[reservationIndex];
  const selectedConfirmReservation = reservations[confirmResIndex];

  const getBatchActions = () => {
    if (!selectedBatch) return [];
    const actions: { label: string; action: string }[] = [];
    if (selectedBatch.status === 'AVAILABLE' || selectedBatch.status === 'EXPIRING_SOON') {
      actions.push({ label: 'Sperren', action: 'block' });
      actions.push({ label: 'Entfernen', action: 'remove' });
    }
    if (selectedBatch.status === 'BLOCKED') {
      actions.push({ label: 'Entsperren', action: 'unblock' });
    }
    if (selectedBatch.status === 'EXPIRED') {
      actions.push({ label: 'Entfernen', action: 'remove' });
    }
    return actions;
  };

  const batchActions = getBatchActions();

  const handleBlock = async () => {
    if (!selectedBatch || !blockReason.trim()) return;
    const result = await blockBatch(stockId, selectedBatch.id!, blockReason.trim());
    if (result) {
      setSuccess('Charge gesperrt.');
      setMode('view');
      setBlockReason('');
    }
  };

  const handleUnblock = async () => {
    if (!selectedBatch) return;
    const result = await unblockBatch(stockId, selectedBatch.id!);
    if (result) {
      setSuccess('Charge entsperrt.');
      setMode('view');
    }
  };

  const handleRemove = async () => {
    if (!selectedBatch || !removeAmount.trim() || !removeUnit.trim()) return;
    const result = await removeBatch(stockId, selectedBatch.id!, removeAmount.trim(), removeUnit.trim());
    if (result) {
      setSuccess('Menge entfernt.');
      setMode('view');
      setRemoveAmount('');
      setRemoveUnit('');
    }
  };

  const handleBatchAction = (action: string) => {
    switch (action) {
      case 'block':
        setMode('block-reason');
        setBlockReason('');
        break;
      case 'unblock':
        void handleUnblock();
        break;
      case 'remove':
        setMode('remove-amount');
        setRemoveAmount('');
        setRemoveUnit('');
        break;
    }
  };

  const handleReleaseReservation = async () => {
    if (!selectedReservation?.id) return;
    const result = await releaseReservation(stockId, selectedReservation.id);
    if (result) {
      setSuccess('Reservierung freigegeben.');
      setMode('view');
      setReservationIndex(0);
    }
  };

  const handleConfirmReservation = async () => {
    if (!selectedConfirmReservation?.id) return;
    const result = await confirmReservation(stockId, selectedConfirmReservation.id);
    if (result) {
      setSuccess('Reservierung bestätigt – Material entnommen.');
      setMode('view');
      setConfirmResIndex(0);
    }
  };

  const MENU_ITEMS = [
    { label: 'Chargen verwalten', action: 'batches' },
    { label: 'Bestand reservieren', action: 'reserve' },
    ...(reservations.length > 0 ? [{ label: 'Reservierung freigeben', action: 'release-reservation' }] : []),
    ...(reservations.length > 0 ? [{ label: 'Reservierung bestätigen', action: 'confirm-reservation' }] : []),
  ];

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

    if (mode === 'block-reason') {
      if (key.escape) setMode('batch-actions');
      return;
    }

    if (mode === 'remove-amount') {
      if (key.escape) setMode('batch-actions');
      return;
    }

    if (mode === 'remove-unit') {
      if (key.escape) setMode('remove-amount');
      return;
    }

    if (mode === 'confirm-confirm-reservation') {
      if (input.toLowerCase() === 'j') {
        void handleConfirmReservation();
      }
      if (input.toLowerCase() === 'n' || key.escape) setMode('confirm-reservation-actions');
      return;
    }

    if (mode === 'confirm-reservation-actions') {
      if (key.upArrow) setConfirmResIndex((i) => Math.max(0, i - 1));
      if (key.downArrow) setConfirmResIndex((i) => Math.min(reservations.length - 1, i + 1));
      if (key.return && reservations[confirmResIndex]) {
        setMode('confirm-confirm-reservation');
      }
      if (key.escape) setMode('view');
      return;
    }

    if (mode === 'confirm-release-reservation') {
      if (input.toLowerCase() === 'j') {
        void handleReleaseReservation();
      }
      if (input.toLowerCase() === 'n' || key.escape) setMode('reservation-actions');
      return;
    }

    if (mode === 'reservation-actions') {
      if (key.upArrow) setReservationIndex((i) => Math.max(0, i - 1));
      if (key.downArrow) setReservationIndex((i) => Math.min(reservations.length - 1, i + 1));
      if (key.return && selectedReservation) {
        setMode('confirm-release-reservation');
      }
      if (key.escape) setMode('view');
      return;
    }

    if (mode === 'batch-actions') {
      if (key.upArrow) setBatchActionIndex((i) => Math.max(0, i - 1));
      if (key.downArrow) setBatchActionIndex((i) => Math.min(batchActions.length - 1, i + 1));
      if (key.return && batchActions[batchActionIndex]) {
        handleBatchAction(batchActions[batchActionIndex].action);
      }
      if (key.escape) setMode('view');
      if (key.leftArrow) setBatchIndex((i) => Math.max(0, i - 1));
      if (key.rightArrow) setBatchIndex((i) => Math.min(batches.length - 1, i + 1));
      return;
    }

    if (mode === 'menu') {
      if (key.upArrow) setMenuIndex((i) => Math.max(0, i - 1));
      if (key.downArrow) setMenuIndex((i) => Math.min(MENU_ITEMS.length - 1, i + 1));
      if (key.return && MENU_ITEMS[menuIndex]) {
        const action = MENU_ITEMS[menuIndex].action;
        if (action === 'batches' && batches.length > 0) {
          setMode('batch-actions');
          setBatchIndex(0);
          setBatchActionIndex(0);
        } else if (action === 'reserve') {
          navigate('stock-reserve', { stockId });
        } else if (action === 'release-reservation') {
          setMode('reservation-actions');
          setReservationIndex(0);
        } else if (action === 'confirm-reservation') {
          setMode('confirm-reservation-actions');
          setConfirmResIndex(0);
        }
      }
      if (key.escape) setMode('view');
      return;
    }

    // view mode
    if (input === 'm') {
      setMode('menu');
      setMenuIndex(0);
    }
    if (key.backspace || key.escape) back();
  });

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

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

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

      {error && <ErrorDisplay message={error} onDismiss={clearError} />}
      {success && <SuccessDisplay message={success} onDismiss={() => setSuccess(null)} />}

      <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={1}>
        <Box><Text color="gray">Artikel:      </Text><Text>{articleName(stock.articleId)}</Text></Box>
        <Box><Text color="gray">Lagerort:     </Text><Text>{locationName(stock.storageLocationId)}</Text></Box>
        <Box><Text color="gray">Gesamtmenge:  </Text><Text>{stock.totalQuantity}{stock.quantityUnit ? ` ${stock.quantityUnit}` : ''}</Text></Box>
        <Box><Text color="gray">Verfügbar:    </Text><Text color="green">{stock.availableQuantity}{stock.quantityUnit ? ` ${stock.quantityUnit}` : ''}</Text></Box>
        {stock.minimumLevel && (
          <Box><Text color="gray">Mindestbest.: </Text><Text>{stock.minimumLevel.amount} {stock.minimumLevel.unit}</Text></Box>
        )}
        {stock.minimumShelfLifeDays != null && (
          <Box><Text color="gray">Min-MHD (d):  </Text><Text>{stock.minimumShelfLifeDays}</Text></Box>
        )}
      </Box>

      {/* Batches table */}
      <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={1}>
        <Text color="cyan" bold>Chargen ({batches.length})</Text>
        {batches.length === 0 ? (
          <Text color="gray" dimColor>Keine Chargen vorhanden.</Text>
        ) : (
          <>
            <Box paddingX={1}>
              <Text color="gray" bold>{'  Batch-ID'.padEnd(18)}</Text>
              <Text color="gray" bold>{'Typ'.padEnd(12)}</Text>
              <Text color="gray" bold>{'Menge'.padEnd(12)}</Text>
              <Text color="gray" bold>{'MHD'.padEnd(14)}</Text>
              <Text color="gray" bold>Status</Text>
            </Box>
            {batches.map((b, i) => {
              const isSelected = mode === 'batch-actions' && i === batchIndex;
              const textColor = isSelected ? 'cyan' : 'white';
              const statusColor = BATCH_STATUS_COLORS[b.status ?? ''] ?? 'white';
              const statusLabel = STOCK_BATCH_STATUS_LABELS[(b.status ?? '') as StockBatchStatus] ?? b.status;
              return (
                <Box key={b.id} paddingX={1}>
                  <Text color={textColor}>{isSelected ? '▶ ' : '  '}</Text>
                  <Text color={textColor}>{(b.batchId ?? '').substring(0, 14).padEnd(15)}</Text>
                  <Text color={isSelected ? 'cyan' : 'gray'}>{(b.batchType ?? '').padEnd(12)}</Text>
                  <Text color={isSelected ? 'cyan' : 'gray'}>{`${b.quantityAmount ?? ''} ${b.quantityUnit ?? ''}`.padEnd(12)}</Text>
                  <Text color={isSelected ? 'cyan' : 'gray'}>{(b.expiryDate ?? '').padEnd(14)}</Text>
                  <Text color={isSelected ? 'cyan' : statusColor}>{statusLabel}</Text>
                </Box>
              );
            })}
          </>
        )}
      </Box>

      {/* Reservations table */}
      {reservations.length > 0 && (
        <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={1}>
          <Text color="cyan" bold>Reservierungen ({reservations.length})</Text>
          <Box paddingX={1}>
            <Text color="gray" bold>{'  Typ'.padEnd(22)}</Text>
            <Text color="gray" bold>{'Referenz'.padEnd(18)}</Text>
            <Text color="gray" bold>{'Menge'.padEnd(14)}</Text>
            <Text color="gray" bold>{'Priorität'.padEnd(12)}</Text>
            <Text color="gray" bold>Reserviert am</Text>
          </Box>
          {reservations.map((r, i) => {
            const isSelected = (mode === 'reservation-actions' && i === reservationIndex) || (mode === 'confirm-reservation-actions' && i === confirmResIndex);
            const textColor = isSelected ? 'cyan' : 'white';
            const refLabel = REFERENCE_TYPE_LABELS[(r.referenceType ?? '') as ReferenceType] ?? r.referenceType;
            const prioLabel = RESERVATION_PRIORITY_LABELS[(r.priority ?? '') as ReservationPriority] ?? r.priority;
            const dateStr = r.reservedAt ? new Date(r.reservedAt).toLocaleDateString('de-DE') : '';
            return (
              <Box key={r.id} paddingX={1}>
                <Text color={textColor}>{isSelected ? '▶ ' : '  '}</Text>
                <Text color={textColor}>{(refLabel ?? '').padEnd(20)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{(r.referenceId ?? '').substring(0, 16).padEnd(16)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{`${r.quantityAmount ?? ''} ${r.quantityUnit ?? ''}`.padEnd(14)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{(prioLabel ?? '').padEnd(12)}</Text>
                <Text color={isSelected ? 'cyan' : 'gray'}>{dateStr}</Text>
              </Box>
            );
          })}
        </Box>
      )}

      {/* Modes */}
      {mode === 'menu' && (
        <Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1}>
          <Text color="cyan" bold>Aktionen</Text>
          {MENU_ITEMS.map((item, i) => (
            <Text key={item.action} color={i === menuIndex ? 'cyan' : 'white'}>
              {i === menuIndex ? '▶ ' : '  '}{item.label}
            </Text>
          ))}
          <Text color="gray" dimColor>↑↓ nav · Enter ausführen · Escape zurück</Text>
        </Box>
      )}

      {mode === 'batch-actions' && selectedBatch && (
        <Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1}>
          <Text color="cyan" bold>Charge: {selectedBatch.batchId} — Aktionen</Text>
          {batchActions.length === 0 ? (
            <Text color="gray" dimColor>Keine Aktionen verfügbar.</Text>
          ) : (
            batchActions.map((a, i) => (
              <Text key={a.action} color={i === batchActionIndex ? 'cyan' : 'white'}>
                {i === batchActionIndex ? '▶ ' : '  '}{a.label}
              </Text>
            ))
          )}
          <Text color="gray" dimColor>←→ Charge wechseln · ↑↓ Aktion · Enter ausführen · Escape zurück</Text>
        </Box>
      )}

      {mode === 'block-reason' && (
        <Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1}>
          <Text color="yellow" bold>Sperrgrund eingeben:</Text>
          <Box>
            <Text color="gray"> › </Text>
            <TextInput
              value={blockReason}
              onChange={setBlockReason}
              onSubmit={() => void handleBlock()}
              focus={true}
            />
          </Box>
          <Text color="gray" dimColor>Enter bestätigen · Escape abbrechen</Text>
        </Box>
      )}

      {mode === 'remove-amount' && (
        <Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1}>
          <Text color="yellow" bold>Zu entfernende Menge:</Text>
          <Box>
            <Text color="gray"> › </Text>
            <TextInput
              value={removeAmount}
              onChange={setRemoveAmount}
              onSubmit={() => setMode('remove-unit')}
              focus={true}
            />
          </Box>
          <Text color="gray" dimColor>Enter weiter · Escape abbrechen</Text>
        </Box>
      )}

      {mode === 'remove-unit' && (
        <Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1}>
          <Text color="yellow" bold>Mengeneinheit (z.B. KILOGRAM):</Text>
          <Box>
            <Text color="gray"> › </Text>
            <TextInput
              value={removeUnit}
              onChange={setRemoveUnit}
              onSubmit={() => void handleRemove()}
              focus={true}
            />
          </Box>
          <Text color="gray" dimColor>Enter bestätigen · Escape zurück</Text>
        </Box>
      )}

      {mode === 'reservation-actions' && (
        <Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1}>
          <Text color="cyan" bold>Reservierung auswählen</Text>
          <Text color="gray" dimColor>↑↓ Reservierung wählen · Enter freigeben · Escape zurück</Text>
        </Box>
      )}

      {mode === 'confirm-release-reservation' && selectedReservation && (
        <Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1}>
          <Text color="yellow" bold>Reservierung freigeben?</Text>
          <Text>Referenz: {selectedReservation.referenceType} / {selectedReservation.referenceId}</Text>
          <Text>Menge: {selectedReservation.quantityAmount} {selectedReservation.quantityUnit}</Text>
          <Text color="gray" dimColor>[J] Ja · [N] Nein</Text>
        </Box>
      )}

      {mode === 'confirm-reservation-actions' && (
        <Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1}>
          <Text color="cyan" bold>Reservierung zum Bestätigen auswählen</Text>
          <Text color="gray" dimColor>↑↓ Reservierung wählen · Enter bestätigen · Escape zurück</Text>
        </Box>
      )}

      {mode === 'confirm-confirm-reservation' && selectedConfirmReservation && (
        <Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1}>
          <Text color="yellow" bold>Reservierung bestätigen – Material entnehmen?</Text>
          <Text>Referenz: {selectedConfirmReservation.referenceType} / {selectedConfirmReservation.referenceId}</Text>
          <Text>Menge: {selectedConfirmReservation.quantityAmount} {selectedConfirmReservation.quantityUnit}</Text>
          <Text color="gray" dimColor>[J] Ja · [N] Nein</Text>
        </Box>
      )}

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