import React, { useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../state/navigation-context.js';
import { useStocks } from '../../hooks/useStocks.js';
import { FormInput } from '../shared/FormInput.js';
import { LoadingSpinner } from '../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../shared/ErrorDisplay.js';
import {
  UOM_VALUES,
  UOM_LABELS,
  REFERENCE_TYPE_LABELS,
  RESERVATION_PRIORITY_LABELS,
} from '@effigenix/api-client';
import type { UoM, ReferenceType, ReservationPriority } from '@effigenix/api-client';

type Field = 'referenceType' | 'referenceId' | 'quantity' | 'unit' | 'priority';
const FIELDS: Field[] = ['referenceType', 'referenceId', 'quantity', 'unit', 'priority'];

const FIELD_LABELS: Record<Field, string> = {
  referenceType: 'Referenztyp (←→ wechseln)',
  referenceId: 'Referenz-ID *',
  quantity: 'Menge *',
  unit: 'Mengeneinheit * (←→ wechseln)',
  priority: 'Priorität (←→ wechseln)',
};

const REFERENCE_TYPE_VALUES: ReferenceType[] = ['PRODUCTION_ORDER', 'SALES_ORDER', 'TRANSFER'];
const PRIORITY_VALUES: ReservationPriority[] = ['LOW', 'NORMAL', 'HIGH', 'URGENT'];

export function ReserveStockScreen() {
  const { params, back } = useNavigation();
  const { reserveStock, loading, error, clearError } = useStocks();

  const stockId = params.stockId ?? '';

  const [refTypeIdx, setRefTypeIdx] = useState(0);
  const [referenceId, setReferenceId] = useState('');
  const [quantity, setQuantity] = useState('');
  const [uomIdx, setUomIdx] = useState(0);
  const [priorityIdx, setPriorityIdx] = useState(1); // NORMAL default
  const [activeField, setActiveField] = useState<Field>('referenceType');
  const [fieldErrors, setFieldErrors] = useState<Partial<Record<Field, string>>>({});
  const [success, setSuccess] = useState(false);

  const handleSubmit = async () => {
    const errors: Partial<Record<Field, string>> = {};
    if (!referenceId.trim()) errors.referenceId = 'Referenz-ID ist erforderlich.';
    if (!quantity.trim()) errors.quantity = 'Menge ist erforderlich.';
    setFieldErrors(errors);
    if (Object.keys(errors).length > 0) return;

    const result = await reserveStock(stockId, {
      referenceType: REFERENCE_TYPE_VALUES[refTypeIdx] as string,
      referenceId: referenceId.trim(),
      quantityAmount: quantity.trim(),
      quantityUnit: UOM_VALUES[uomIdx] as string,
      priority: PRIORITY_VALUES[priorityIdx] as string,
    });
    if (result) setSuccess(true);
  };

  const handleFieldSubmit = (field: Field) => (_value: string) => {
    const idx = FIELDS.indexOf(field);
    if (idx < FIELDS.length - 1) {
      setActiveField(FIELDS[idx + 1] ?? field);
    } else {
      void handleSubmit();
    }
  };

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

    if (success) {
      if (key.return || key.escape) back();
      return;
    }

    if (activeField === 'referenceType') {
      if (key.leftArrow || key.rightArrow) {
        const dir = key.rightArrow ? 1 : -1;
        setRefTypeIdx((i) => (i + dir + REFERENCE_TYPE_VALUES.length) % REFERENCE_TYPE_VALUES.length);
        return;
      }
      if (key.return || key.tab) {
        setActiveField('referenceId');
        return;
      }
      if (key.escape) { back(); return; }
    }

    if (activeField === 'unit') {
      if (key.leftArrow || key.rightArrow) {
        const dir = key.rightArrow ? 1 : -1;
        setUomIdx((i) => (i + dir + UOM_VALUES.length) % UOM_VALUES.length);
        return;
      }
      if (key.return) {
        handleFieldSubmit('unit')('');
        return;
      }
    }

    if (activeField === 'priority') {
      if (key.leftArrow || key.rightArrow) {
        const dir = key.rightArrow ? 1 : -1;
        setPriorityIdx((i) => (i + dir + PRIORITY_VALUES.length) % PRIORITY_VALUES.length);
        return;
      }
      if (key.return) {
        void handleSubmit();
        return;
      }
    }

    if (key.tab || key.downArrow) {
      setActiveField((f) => {
        const idx = FIELDS.indexOf(f);
        return FIELDS[(idx + 1) % FIELDS.length] ?? f;
      });
    }
    if (key.upArrow) {
      setActiveField((f) => {
        const idx = FIELDS.indexOf(f);
        return FIELDS[(idx - 1 + FIELDS.length) % FIELDS.length] ?? f;
      });
    }
    if (key.escape) back();
  });

  if (loading) {
    return (
      <Box flexDirection="column" alignItems="center" paddingY={2}>
        <LoadingSpinner label="Bestand wird reserviert..." />
      </Box>
    );
  }

  if (success) {
    return (
      <Box flexDirection="column" gap={1} paddingY={1}>
        <Text color="green" bold>Bestand erfolgreich reserviert!</Text>
        <Text color="gray" dimColor>Enter/Escape zum Zurückkehren</Text>
      </Box>
    );
  }

  const refTypeLabel = REFERENCE_TYPE_LABELS[REFERENCE_TYPE_VALUES[refTypeIdx] as ReferenceType] ?? REFERENCE_TYPE_VALUES[refTypeIdx];
  const uomLabel = UOM_LABELS[UOM_VALUES[uomIdx] as UoM] ?? UOM_VALUES[uomIdx];
  const priorityLabel = RESERVATION_PRIORITY_LABELS[PRIORITY_VALUES[priorityIdx] as ReservationPriority] ?? PRIORITY_VALUES[priorityIdx];

  return (
    <Box flexDirection="column" gap={1}>
      <Text color="cyan" bold>Bestand reservieren</Text>
      {error && <ErrorDisplay message={error} onDismiss={clearError} />}

      <Box flexDirection="column" gap={1} width={60}>
        {/* Reference Type */}
        <Box flexDirection="column">
          <Text color={activeField === 'referenceType' ? 'cyan' : 'gray'}>
            {FIELD_LABELS.referenceType}: <Text bold color="white">{activeField === 'referenceType' ? `< ${refTypeLabel} >` : refTypeLabel}</Text>
          </Text>
        </Box>

        {/* Reference ID */}
        <FormInput
          label={FIELD_LABELS.referenceId}
          value={referenceId}
          onChange={setReferenceId}
          onSubmit={handleFieldSubmit('referenceId')}
          focus={activeField === 'referenceId'}
          {...(fieldErrors.referenceId ? { error: fieldErrors.referenceId } : {})}
        />

        {/* Quantity */}
        <FormInput
          label={FIELD_LABELS.quantity}
          value={quantity}
          onChange={setQuantity}
          onSubmit={handleFieldSubmit('quantity')}
          focus={activeField === 'quantity'}
          {...(fieldErrors.quantity ? { error: fieldErrors.quantity } : {})}
        />

        {/* Unit */}
        <Box flexDirection="column">
          <Text color={activeField === 'unit' ? 'cyan' : 'gray'}>
            {FIELD_LABELS.unit}: <Text bold color="white">{activeField === 'unit' ? `< ${uomLabel} >` : uomLabel}</Text>
          </Text>
        </Box>

        {/* Priority */}
        <Box flexDirection="column">
          <Text color={activeField === 'priority' ? 'cyan' : 'gray'}>
            {FIELD_LABELS.priority}: <Text bold color="white">{activeField === 'priority' ? `< ${priorityLabel} >` : priorityLabel}</Text>
          </Text>
        </Box>
      </Box>

      <Box marginTop={1}>
        <Text color="gray" dimColor>
          Tab/↑↓ Feld wechseln · ←→ Typ/Einheit/Priorität · Enter bestätigen/speichern · Escape Abbrechen
        </Text>
      </Box>
    </Box>
  );
}
