// Copyright © 2022 Olo Inc. All rights reserved.
// This software is made available under the Olo Pay SDK License (See LICENSE.md file)
import {
  codegenNativeComponent,
  codegenNativeCommands,
  type ViewProps,
  type HostComponent,
} from 'react-native';
import type {
  DirectEventHandler,
  Double,
  WithDefault,
} from 'react-native/Libraries/Types/CodegenTypes';

// Event types - inline definitions required for codegen (mirrors types in definitions.ts)
interface CvvDetailsEventData {
  state: {
    isValid: boolean;
    isFocused: boolean;
    isEmpty: boolean;
    wasEdited: boolean;
    wasFocused: boolean;
  };
  errors?: {
    uneditedFieldError?: string;
    editedFieldError?: string;
  };
}

// Inline type required for codegen - mirrors CvvTokenResult from definitions.ts
interface CvvTokenResultEventData {
  token?: {
    id: string;
    productionEnvironment: boolean;
  };
  error?: {
    code: string;
    message: string;
  };
}

// Nested style object for CVV styles
export interface PaymentCardCvvNativeViewStyles {
  backgroundColor?: string;
  borderColor?: string;
  borderWidth?: Double;
  cornerRadius?: Double;
  cursorColor?: string;
  fontFamily?: string;
  fontSize?: Double;
  placeholderColor?: string;
  textColor?: string;
  errorTextColor?: string;
  textPaddingLeft?: Double;
  textPaddingRight?: Double;
  fontWeight?: string;
  italic?: boolean;
  textAlign?: string;
}

// Custom error messages
export interface CvvCustomErrorMessages {
  emptyError?: string;
  invalidError?: string;
}

export interface NativeProps extends ViewProps {
  isEnabled?: WithDefault<boolean, true>;
  cvvStyles?: PaymentCardCvvNativeViewStyles;
  placeholder?: string;
  customErrorMessages?: CvvCustomErrorMessages;

  // Events
  onCvvChangeEvent?: DirectEventHandler<CvvDetailsEventData>;
  onFocusEvent?: DirectEventHandler<CvvDetailsEventData>;
  onBlurEvent?: DirectEventHandler<CvvDetailsEventData>;
  onCvvTokenResultEvent?: DirectEventHandler<CvvTokenResultEventData>;
}

// Command definitions for native methods
interface NativeCommands {
  focus: (viewRef: React.ElementRef<HostComponent<NativeProps>>) => void;
  blur: (viewRef: React.ElementRef<HostComponent<NativeProps>>) => void;
  clear: (viewRef: React.ElementRef<HostComponent<NativeProps>>) => void;
  createCvvUpdateToken: (viewRef: React.ElementRef<HostComponent<NativeProps>>) => void;
}

export const Commands: NativeCommands = codegenNativeCommands<NativeCommands>({
  supportedCommands: ['focus', 'blur', 'clear', 'createCvvUpdateToken'],
});

export default codegenNativeComponent<NativeProps>(
  'PaymentCardCvvView'
) as HostComponent<NativeProps>;
