import React from 'react';
import { TextInput } from 'react-native';
import { FormField } from '../components/FormField';
import { validateCVCFn } from '../utils/validateCVCFn';
import { FieldState } from './CreateCardForTemporaryUseForm';
import type {
  DuffelCardFormProps,
  DuffelCardFormStrings,
  DuffelCardFormStyles,
  UseSavedCardPayload,
} from '../../../index';

interface UseSavedCardFormProps {
  data: UseSavedCardPayload;
  onChange: (data: UseSavedCardPayload) => void;

  onValidateSuccess: DuffelCardFormProps['onValidateSuccess'];
  onValidateFailure: DuffelCardFormProps['onValidateFailure'];

  inputStyle: DuffelCardFormStyles['input'];
  formFieldStyle: DuffelCardFormStyles['formField'];
  errorMessageStyle: DuffelCardFormStyles['errorMessage'];

  customStrings: DuffelCardFormStrings;
}

export const UseSavedCardForm: React.FC<UseSavedCardFormProps> = ({
  data,
  onChange,
  onValidateSuccess,
  onValidateFailure,
  inputStyle,
  formFieldStyle,
  errorMessageStyle,
  customStrings,
}) => {
  const [hasEmittedValidationState, setHasEmittedValidationState] =
    React.useState(false);

  const [fieldState, setFieldState] = React.useState<FieldState>({
    touched: false,
    valid: false,
    error: null,
  });

  const validateCVC = validateCVCFn(customStrings);

  return (
    <FormField
      error={
        fieldState.touched && fieldState.error !== null ? fieldState.error : ''
      }
      formFieldStyle={formFieldStyle}
      errorMessageStyles={errorMessageStyle}
    >
      <TextInput
        testID="cvc"
        keyboardType="numeric"
        style={inputStyle}
        value={data.cvc}
        onChange={(e) => {
          const cvc = e.nativeEvent.text;
          onChange({ ...data, cvc });

          const { valid, error } = validateCVC(cvc);
          setFieldState({ touched: fieldState.touched, valid, error });

          if (valid) {
            onValidateSuccess();
            setHasEmittedValidationState(true);
          }
        }}
        onEndEditing={() => {
          const { valid, error } = validateCVC(data.cvc);
          setFieldState({ touched: true, valid, error });
          if (hasEmittedValidationState && !valid) {
            onValidateFailure();
          }
        }}
        placeholder={customStrings.cvvPlaceholder}
      />
    </FormField>
  );
};
