import React, { useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../../state/navigation-context.js';
import { useSuppliers } from '../../../hooks/useSuppliers.js';
import { FormInput } from '../../shared/FormInput.js';
import { LoadingSpinner } from '../../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../../shared/ErrorDisplay.js';

type Field = 'certificateType' | 'issuer' | 'validFrom' | 'validUntil';
const FIELDS: Field[] = ['certificateType', 'issuer', 'validFrom', 'validUntil'];

const FIELD_LABELS: Record<Field, string> = {
  certificateType: 'Zertifikat-Typ *',
  issuer: 'Aussteller *',
  validFrom: 'Gültig ab * (YYYY-MM-DD)',
  validUntil: 'Gültig bis * (YYYY-MM-DD)',
};

function isValidDate(s: string): boolean {
  return /^\d{4}-\d{2}-\d{2}$/.test(s) && !isNaN(Date.parse(s));
}

export function AddCertificateScreen() {
  const { params, replace, back } = useNavigation();
  const supplierId = params['supplierId'] ?? '';
  const { addCertificate, loading, error, clearError } = useSuppliers();

  const [values, setValues] = useState<Record<Field, string>>({
    certificateType: '',
    issuer: '',
    validFrom: '',
    validUntil: '',
  });
  const [activeField, setActiveField] = useState<Field>('certificateType');
  const [fieldErrors, setFieldErrors] = useState<Partial<Record<Field, string>>>({});

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

  useInput((_input, key) => {
    if (loading) 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();
  });

  const handleSubmit = async () => {
    const errors: Partial<Record<Field, string>> = {};
    if (!values.certificateType.trim()) errors.certificateType = 'Typ ist erforderlich.';
    if (!values.issuer.trim()) errors.issuer = 'Aussteller ist erforderlich.';
    if (!isValidDate(values.validFrom)) errors.validFrom = 'Ungültiges Datum (YYYY-MM-DD).';
    if (!isValidDate(values.validUntil)) errors.validUntil = 'Ungültiges Datum (YYYY-MM-DD).';
    setFieldErrors(errors);
    if (Object.keys(errors).length > 0) return;

    const updated = await addCertificate(supplierId, {
      certificateType: values.certificateType.trim().toUpperCase(),
      issuer: values.issuer.trim(),
      validFrom: values.validFrom,
      validUntil: values.validUntil,
    });
    if (updated) replace('supplier-detail', { supplierId });
  };

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

  if (loading) return <LoadingSpinner label="Zertifikat wird hinzugefügt..." />;

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

      <Box flexDirection="column" gap={1} width={60}>
        {FIELDS.map((field) => (
          <FormInput
            key={field}
            label={FIELD_LABELS[field]}
            value={values[field]}
            onChange={setField(field)}
            onSubmit={handleFieldSubmit(field)}
            focus={activeField === field}
            placeholder={field.includes('valid') ? '2025-01-01' : ''}
            {...(fieldErrors[field] ? { error: fieldErrors[field] } : {})}
          />
        ))}
      </Box>

      <Box marginTop={1}>
        <Text color="gray" dimColor>
          Tab/↑↓ Feld wechseln · Enter auf letztem Feld speichern · Escape Abbrechen
        </Text>
      </Box>
    </Box>
  );
}
