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 { useBatches } from '../../hooks/useBatches.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 { BATCH_STATUS_LABELS, UOM_LABELS } from '@effigenix/api-client';
import type { BatchStatus, UoM } from '@effigenix/api-client';

type Mode = 'view' | 'menu' | 'confirm-start' | 'confirm-cancel' | 'cancel-reason';

const STATUS_COLORS: Record<string, string> = {
  PLANNED: 'yellow',
  IN_PRODUCTION: 'blue',
  COMPLETED: 'green',
  CANCELLED: 'red',
};

export function BatchDetailScreen() {
  const { params, navigate, back } = useNavigation();
  const { batch, loading, error, fetchBatch, startBatch, cancelBatch, clearError } = useBatches();
  const [mode, setMode] = useState<Mode>('view');
  const [menuIndex, setMenuIndex] = useState(0);
  const [success, setSuccess] = useState<string | null>(null);
  const [cancelReason, setCancelReason] = useState('');

  const batchId = params.batchId ?? '';

  useEffect(() => {
    if (batchId) void fetchBatch(batchId);
  }, [fetchBatch, batchId]);

  const getMenuItems = () => {
    if (!batch) return [];
    const items: { label: string; action: string }[] = [];
    if (batch.status === 'PLANNED') {
      items.push({ label: 'Charge starten', action: 'start' });
      items.push({ label: 'Charge stornieren', action: 'cancel' });
    }
    if (batch.status === 'IN_PRODUCTION') {
      items.push({ label: 'Verbrauch erfassen', action: 'consumption' });
      items.push({ label: 'Charge abschließen', action: 'complete' });
      items.push({ label: 'Charge stornieren', action: 'cancel' });
    }
    return items;
  };

  const menuItems = getMenuItems();

  const handleMenuAction = (action: string) => {
    switch (action) {
      case 'start':
        setMode('confirm-start');
        break;
      case 'cancel':
        setMode('cancel-reason');
        setCancelReason('');
        break;
      case 'consumption':
        navigate('batch-record-consumption', { batchId });
        break;
      case 'complete':
        navigate('batch-complete', { batchId });
        break;
    }
  };

  const handleStart = async () => {
    const result = await startBatch(batchId);
    if (result) {
      setSuccess('Charge wurde gestartet.');
      setMode('view');
    }
  };

  const handleCancel = async () => {
    if (!cancelReason.trim()) return;
    const result = await cancelBatch(batchId, cancelReason.trim());
    if (result) {
      setSuccess('Charge wurde storniert.');
      setMode('view');
    }
  };

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

    if (mode === 'cancel-reason') {
      if (key.escape) setMode('view');
      return;
    }

    if (mode === 'confirm-start' || mode === 'confirm-cancel') return;

    if (mode === 'menu') {
      if (key.upArrow) setMenuIndex((i) => Math.max(0, i - 1));
      if (key.downArrow) setMenuIndex((i) => Math.min(menuItems.length - 1, i + 1));
      if (key.return && menuItems[menuIndex]) {
        handleMenuAction(menuItems[menuIndex].action);
      }
      if (key.escape) setMode('view');
      return;
    }

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

  if (loading && !batch) {
    return <LoadingSpinner label="Lade Charge..." />;
  }

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

  const statusLabel = BATCH_STATUS_LABELS[batch.status as BatchStatus] ?? batch.status;
  const statusColor = STATUS_COLORS[batch.status ?? ''] ?? 'white';
  const uomLabel = (u: string | undefined) => (u ? UOM_LABELS[u as UoM] ?? u : '');

  return (
    <Box flexDirection="column" gap={1}>
      <Box gap={2}>
        <Text color="cyan" bold>Charge: {batch.batchNumber}</Text>
        <Text color={statusColor} bold>[{statusLabel}]</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">Rezept-ID:      </Text><Text>{batch.recipeId}</Text></Box>
        <Box><Text color="gray">Geplante Menge: </Text><Text>{batch.plannedQuantity} {uomLabel(batch.plannedQuantityUnit)}</Text></Box>
        <Box><Text color="gray">Prod.-Datum:    </Text><Text>{batch.productionDate}</Text></Box>
        <Box><Text color="gray">MHD:            </Text><Text>{batch.bestBeforeDate}</Text></Box>
        {batch.actualQuantity && (
          <Box><Text color="gray">Ist-Menge:      </Text><Text>{batch.actualQuantity} {uomLabel(batch.actualQuantityUnit)}</Text></Box>
        )}
        {batch.waste && (
          <Box><Text color="gray">Ausschuss:      </Text><Text>{batch.waste} {uomLabel(batch.wasteUnit)}</Text></Box>
        )}
        {batch.remarks && (
          <Box><Text color="gray">Bemerkungen:    </Text><Text>{batch.remarks}</Text></Box>
        )}
        {batch.completedAt && (
          <Box><Text color="gray">Abgeschlossen:  </Text><Text>{new Date(batch.completedAt).toLocaleString('de-DE')}</Text></Box>
        )}
        {batch.cancellationReason && (
          <Box><Text color="gray">Stornogrund:    </Text><Text color="red">{batch.cancellationReason}</Text></Box>
        )}
        {batch.cancelledAt && (
          <Box><Text color="gray">Storniert am:   </Text><Text>{new Date(batch.cancelledAt).toLocaleString('de-DE')}</Text></Box>
        )}
      </Box>

      {/* Consumptions */}
      {batch.consumptions && batch.consumptions.length > 0 && (
        <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={1}>
          <Text color="cyan" bold>Verbrauchsmaterial ({batch.consumptions.length})</Text>
          <Box paddingX={1}>
            <Text color="gray" bold>{'Artikel'.padEnd(20)}</Text>
            <Text color="gray" bold>{'Menge'.padEnd(16)}</Text>
            <Text color="gray" bold>Erfasst am</Text>
          </Box>
          {batch.consumptions.map((c) => (
            <Box key={c.id} paddingX={1}>
              <Text>{(c.articleId ?? '').substring(0, 18).padEnd(20)}</Text>
              <Text>{`${c.quantityUsed ?? ''} ${uomLabel(c.quantityUsedUnit)}`.padEnd(16)}</Text>
              <Text color="gray">{c.consumedAt ? new Date(c.consumedAt).toLocaleString('de-DE') : ''}</Text>
            </Box>
          ))}
        </Box>
      )}

      {/* Modes */}
      {mode === 'menu' && (
        <Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1}>
          <Text color="cyan" bold>Aktionen</Text>
          {menuItems.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 === 'confirm-start' && (
        <ConfirmDialog
          message="Charge starten? Status wird auf 'In Produktion' gesetzt."
          onConfirm={() => void handleStart()}
          onCancel={() => setMode('view')}
        />
      )}

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

      <Box marginTop={1}>
        <Text color="gray" dimColor>
          {menuItems.length > 0 ? '[m] Aktionsmenü · ' : ''}Backspace Zurück
        </Text>
      </Box>
    </Box>
  );
}
