import React, { Component } from "react";
import { Modal, ModalBody } from 'reactstrap';
import "../../sabpaisa-css-utils-classes-version-five.css"
import "../../index.css";

import ClientDetails from "./Sections/ClientDetails";
import { decAESString } from "../../helpers/common-helper";


export interface PgModalProps {
  isOpen?: boolean;
  clientCode: string;
  clientTxnId: string;
  transUserName: string,
  transUserPassword: string;
  authkey: string;
  authiv: string;
  payerName: string,
  payerEmail: string,
  payerMobile: string,
  payerAddress: string,
  amount: string,
  amountType: string,
  udf1: string,
  udf2: string,
  udf3: string,
  udf4: string,
  udf5: string,
  udf6: string,
  udf7: string,
  udf8: string,
  udf9: string,
  udf10: string,
  udf11: string,
  udf12: string,
  udf13: string,
  udf14: string,
  udf15: string,
  udf16: string,
  udf17: string,
  udf18: string,
  udf19: string,
  udf20: string,
  channelId: string,
  programId: string,
  mcc: string,
  onToggle?: (
    event: React.MouseEvent<HTMLButtonElement, MouseEvent>
  ) => void;
  env: string;
  additionalClass?: string;
}
type State = {
  submitted: boolean,
  isOpen: boolean | false,
  currentState: number,
  errorMessage: string,
  paymentData: { [key: string]: any },
  activeMappings: {}[],
  isResponsed: boolean;

};
export default class PgModal extends Component<PgModalProps, State> {
  constructor(props: PgModalProps) {
    super(props);
    this.state = {
      submitted: false,
      isOpen: this.props.isOpen ?? false,
      currentState: 0,
      paymentData: {},
      activeMappings: [],
      errorMessage: '',
      isResponsed: false
    };
  }
  componentDidMount(): void {
    const urlParams = new URLSearchParams(window.location.search);
    const encResponse = urlParams.get('encResponse');
    const { authkey, authiv } = this.props;

    if (authkey && authiv && encResponse) {

      const decData = decAESString(encResponse.replaceAll(' ', '+'), authkey, authiv)
      window.location.search = decData;
    }
  }

  componentDidUpdate(prevProps: any, preState: any) {
    if (prevProps.isOpen !== this.props.isOpen) {
      this.setState({ isOpen: this.props.isOpen ? true : false });
    }

    if ((typeof (Object.keys(preState.paymentData).length || null) !== typeof Object.keys(this.state.paymentData).length) && (Object.keys(this.state.paymentData).length !== 0)) {
      this.setState({ isResponsed: true });
    }

  }

  render() {
    const { isOpen, isResponsed } = this.state;

    const { onToggle, additionalClass } = this.props;
    return (
      <div id="pg-sdk">
        <Modal isOpen={isOpen ? true : false} wrapClassName="sabpaisa-css-utils-classes-version-five" toggle={onToggle} className={additionalClass} id="pg-sdk">
          <ModalBody id="overlay" close>
            <ClientDetails isResponsed={isResponsed} toggle={onToggle}
              {...this.props} />
          </ModalBody>
        </Modal>

      </div>
    );
  }
}