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 = 'actualQuantity' | 'actualUnit' | 'waste' | 'wasteUnit' | 'remarks';
const FIELDS: Field[] = ['actualQuantity', 'actualUnit', 'waste', 'wasteUnit', 'remarks'];

const FIELD_LABELS: Record<Field, string> = {
  actualQuantity: 'Ist-Menge *',
  actualUnit: 'Ist-Einheit * (←→ wechseln)',
  waste: 'Ausschuss *',
  wasteUnit: 'Ausschuss-Einheit * (←→ wechseln)',
  remarks: 'Bemerkungen',
};

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

  const batchId = params.batchId ?? '';
  const [values, setValues] = useState({ actualQuantity: '', waste: '', remarks: '' });
  const [actualUomIdx, setActualUomIdx] = useState(0);
  const [wasteUomIdx, setWasteUomIdx] = useState(0);
  const [activeField, setActiveField] = useState<Field>('actualQuantity');
  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.actualQuantity.trim()) errors.actualQuantity = 'Ist-Menge erforderlich.';
    if (!values.waste.trim()) errors.waste = 'Ausschuss erforderlich (0 wenn kein Ausschuss).';
    setFieldErrors(errors);
    if (Object.keys(errors).length > 0) return;

    const result = await completeBatch(batchId, {
      actualQuantity: values.actualQuantity.trim(),
      actualQuantityUnit: UOM_VALUES[actualUomIdx] as string,
      waste: values.waste.trim(),
      wasteUnit: UOM_VALUES[wasteUomIdx] as string,
      ...(values.remarks.trim() ? { remarks: values.remarks.trim() } : {}),
    });
    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 === 'actualUnit' || activeField === 'wasteUnit') {
      const setIdx = activeField === 'actualUnit' ? setActualUomIdx : setWasteUomIdx;
      if (key.leftArrow || key.rightArrow) {
        const dir = key.rightArrow ? 1 : -1;
        setIdx((i) => (i + dir + UOM_VALUES.length) % UOM_VALUES.length);
        return;
      }
      if (key.return) {
        handleFieldSubmit(activeField)('');
        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="Charge wird abgeschlossen..." />;

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

  const actualUomLabel = UOM_LABELS[UOM_VALUES[actualUomIdx] as UoM] ?? UOM_VALUES[actualUomIdx];
  const wasteUomLabel = UOM_LABELS[UOM_VALUES[wasteUomIdx] as UoM] ?? UOM_VALUES[wasteUomIdx];

  return (
    <Box flexDirection="column" gap={1}>
      <Text color="cyan" bold>Charge abschließen</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.actualQuantity}
          value={values.actualQuantity}
          onChange={setField('actualQuantity')}
          onSubmit={handleFieldSubmit('actualQuantity')}
          focus={activeField === 'actualQuantity'}
          {...(fieldErrors.actualQuantity ? { error: fieldErrors.actualQuantity } : {})}
        />
        <Box flexDirection="column">
          <Text color={activeField === 'actualUnit' ? 'cyan' : 'gray'}>
            {FIELD_LABELS.actualUnit}: <Text bold color="white">{activeField === 'actualUnit' ? `< ${actualUomLabel} >` : actualUomLabel}</Text>
          </Text>
        </Box>
        <FormInput
          label={FIELD_LABELS.waste}
          value={values.waste}
          onChange={setField('waste')}
          onSubmit={handleFieldSubmit('waste')}
          focus={activeField === 'waste'}
          {...(fieldErrors.waste ? { error: fieldErrors.waste } : {})}
        />
        <Box flexDirection="column">
          <Text color={activeField === 'wasteUnit' ? 'cyan' : 'gray'}>
            {FIELD_LABELS.wasteUnit}: <Text bold color="white">{activeField === 'wasteUnit' ? `< ${wasteUomLabel} >` : wasteUomLabel}</Text>
          </Text>
        </Box>
        <FormInput
          label={FIELD_LABELS.remarks}
          value={values.remarks}
          onChange={setField('remarks')}
          onSubmit={handleFieldSubmit('remarks')}
          focus={activeField === 'remarks'}
        />
      </Box>

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