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

type Field = 'inputBatchId' | 'articleId' | 'quantityUsed' | 'quantityUnit';
const FIELDS: Field[] = ['inputBatchId', 'articleId', 'quantityUsed', 'quantityUnit'];

const FIELD_LABELS: Record<Field, string> = {
  inputBatchId: 'Input-Chargen-ID *',
  articleId: 'Artikel-ID *',
  quantityUsed: 'Verbrauchte Menge *',
  quantityUnit: 'Mengeneinheit * (←→ wechseln)',
};

export function RecordConsumptionScreen() {
  const { params, back } = useNavigation();
  const { recordConsumption, loading, error, clearError } = useBatches();

  const batchId = params.batchId ?? '';
  const [values, setValues] = useState({ inputBatchId: '', articleId: '', quantityUsed: '' });
  const [uomIdx, setUomIdx] = useState(0);
  const [activeField, setActiveField] = useState<Field>('inputBatchId');
  const [fieldErrors, setFieldErrors] = useState<Partial<Record<Field, string>>>({});
  const [success, setSuccess] = useState(false);

  const setField = (field: keyof typeof values) => (value: string) => {
    setValues((v) => ({ ...v, [field]: value }));
  };

  const handleSubmit = async () => {
    const errors: Partial<Record<Field, string>> = {};
    if (!values.inputBatchId.trim()) errors.inputBatchId = 'Chargen-ID erforderlich.';
    if (!values.articleId.trim()) errors.articleId = 'Artikel-ID erforderlich.';
    if (!values.quantityUsed.trim()) errors.quantityUsed = 'Menge erforderlich.';
    setFieldErrors(errors);
    if (Object.keys(errors).length > 0) return;

    const result = await recordConsumption(batchId, {
      inputBatchId: values.inputBatchId.trim(),
      articleId: values.articleId.trim(),
      quantityUsed: values.quantityUsed.trim(),
      quantityUnit: UOM_VALUES[uomIdx] as string,
    });
    if (result) {
      setSuccess(true);
      setTimeout(() => back(), 1500);
    }
  };

  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 || success) return;

    if (activeField === 'quantityUnit') {
      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) {
        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 <LoadingSpinner label="Verbrauch wird erfasst..." />;

  if (success) {
    return (
      <Box flexDirection="column" paddingY={1}>
        <Text color="green" bold>Verbrauch erfolgreich erfasst.</Text>
      </Box>
    );
  }

  const uomLabel = UOM_LABELS[UOM_VALUES[uomIdx] as UoM] ?? UOM_VALUES[uomIdx];

  return (
    <Box flexDirection="column" gap={1}>
      <Text color="cyan" bold>Verbrauch erfassen</Text>
      <Text color="gray" dimColor>Charge: {batchId}</Text>
      {error && <ErrorDisplay message={error} onDismiss={clearError} />}

      <Box flexDirection="column" gap={1} width={60}>
        <FormInput
          label={FIELD_LABELS.inputBatchId}
          value={values.inputBatchId}
          onChange={setField('inputBatchId')}
          onSubmit={handleFieldSubmit('inputBatchId')}
          focus={activeField === 'inputBatchId'}
          {...(fieldErrors.inputBatchId ? { error: fieldErrors.inputBatchId } : {})}
        />
        <FormInput
          label={FIELD_LABELS.articleId}
          value={values.articleId}
          onChange={setField('articleId')}
          onSubmit={handleFieldSubmit('articleId')}
          focus={activeField === 'articleId'}
          {...(fieldErrors.articleId ? { error: fieldErrors.articleId } : {})}
        />
        <FormInput
          label={FIELD_LABELS.quantityUsed}
          value={values.quantityUsed}
          onChange={setField('quantityUsed')}
          onSubmit={handleFieldSubmit('quantityUsed')}
          focus={activeField === 'quantityUsed'}
          {...(fieldErrors.quantityUsed ? { error: fieldErrors.quantityUsed } : {})}
        />
        <Box flexDirection="column">
          <Text color={activeField === 'quantityUnit' ? 'cyan' : 'gray'}>
            {FIELD_LABELS.quantityUnit}: <Text bold color="white">{activeField === 'quantityUnit' ? `< ${uomLabel} >` : uomLabel}</Text>
          </Text>
        </Box>
      </Box>

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