import React, { useState } from "react";
import { connect } from "react-redux";
import { userFactor } from "../../../redux/actions";
import "./index.scss";

function DiscountCode({
  codeId,
  setCodeId,
  delCodeId,
  userId,
  factorId,
  code,
}: any) {
  const [value, setValue] = React.useState(code || "");
  const setOff = () => {
    setCodeId({ offCodeValue: value, userId: userId, id: Number(factorId) || null });
  };
  return (
    <div className="discount-code d-flex align-items-center justify-content-between">
      <h3>کارت هدیه یا کد تخفیف دارید؟ </h3>
      <div className="d-flex flex-column">
        <div className="d-flex">
          {!code ? (
            <>
              <input
                type="text"
                placeholder="کد خود را در این قسمت وارد نمائید"
                defaultValue={codeId}
                onChange={(e) => setValue(e.target.value)}
              />
              <button onClick={setOff}>تایید کد</button>
            </>
          ) : (
            <>
              <p>
                کد تخفیف برای شما ثبت شده است
              </p>
              <button
                onClick={() => delCodeId({})}
                className="discount-code__cancel"
              >
                x{" "}
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

export default connect(
  (state: any) => ({
    codeId: state.userFactor.info?.codeId,
    code: state.userFactor.info?.offCode?.code,
    userId: state.user.status.id,
    factorId: state.userFactor.info?.id,
  }),
  {
    setCodeId: userFactor.update,
    delCodeId: userFactor.deleteUserOffCode,
  }
)(DiscountCode);
