const TelcoOTP = () => {
  const classes = useStyles({});
  const dispatch = useDispatch();
  const variables = useSelector(
    (state: any) => state.process.taskModel.variables
  );
  const telcoInfo = variables?.telcoInfo;
  const client: ClientInfo = variables?.client;
  const businessKey: number = variables?.businessKey;
  const storeSendName = "otpSended";
  const clientDoctypeList = ["УЛ", "ПТ"];


  const [phoneHelperText, setPhoneHelperText] = useState("");
  const [phoneProviders, languages, docTypes, smsMessages] = usePromise4<
    CodeValue[],
    CodeValue[],
    CodeName[],
    CodeValue[]
  >(
    [
      () => api.bccOffline.get<CodeValue[]>("PhoneOperator"),
      () => api.bccOffline.get<CodeValue[]>("SMSLanguage"),
      () => api.bccOffline.get<CodeName[]>("Id"),
      () => api.bccOffline.get<CodeValue[]>("TelcoMessage")
    ],
    [[], [], [], []],
    true
  );
  const changeValue = (object: TelcoInfo) => {
    dispatch(
      updateTaskVariables(
        (c) => c.telcoInfo,
        (p) => object
      )
    );
  };

  useEffect(() => {
    changeValue({
      ...telcoInfo,
      optDateTime: new Date(),
      date: moment().format("DD.MM.yyyy"),
      language: telcoInfo?.language || LANGUAGES.KAZ,
      doctype: telcoInfo?.doctype || DOCUMENTS_TYPE.IDENTITY_CARD
    });

    if (variables?.errors) {
      pm.openSnackBar(variables?.errors, "error");
    }
  }, []);

  const onPhoneChange = (value: string) => {
    changeValue({ ...telcoInfo, "phone": value });
    if (value.replace("_", "").length === 12 && phoneHelperText === "") {
      pm.startLoading(true);
      clientPhoneCheck(value, variables?.resultGIIN?.data[0].iin || "").then((resp) => {
        if (!resp.open) {
          setPhoneHelperText(resp.message);
        } else {
          pm.openSnackBar(resp.message);
        }
        pm.stopLoading(true);
      })
        .catch((e) => {
          pm.openSnackBar(e);
          pm.stopLoading(true);
        });
    }
  };

//Отправка SMS
  const sendSMS = () => {
    pm.startLoading();
    changeValue({
      ...telcoInfo,
      otpSended: true,
      optDateTime: new Date(),
      date: moment().format("DD.MM.yyyy")
    });
    const sms = smsMessages.find((e) => e.code === telcoInfo?.language)?.value?.toString().replace(
      "URL",
      variables?.vars?.SOG_URL + "?msgId=" + variables?.businessKey
    );
    api.colvirRest
      .postProc<{ cresp: any }>("z_077_PkgFront.pSetLogTelco", {
        idbusiness: businessKey,
        sphone: telcoInfo?.phone,
        stext: `${sms}`
      })
      .then((resp) => {
        if (resp.isSuccess) {
          if (resp.data.cresp.status !== "error") {
            pm.openSnackBar("Код подтверждения успешно отправлено!", "success");
            sessionStorage.setItem(storeSendName, "true");
          } else {
            pm.openSnackBar(
              resp.data.cresp?.error?.message ||
              "Ошибка при отправке кода подтверждения!"
            );
          }
        } else {

          pm.openSnackBar(
            resp?.message || "Ошибка при отправке кода подтверждения!"
          );
        }
      })
      .catch((err: Error) => {
        pm.openSnackBar(err.message);
        changeValue({ ...telcoInfo, otpSended: false });
      })
      .finally(() => {
        pm.stopLoading();
      });
  };

  const deb = debounce(() => {
    changeValue({
      ...telcoInfo,
      otpSended: false
    });
  }, 60_000);

  useEffect(() => {
    if (telcoInfo?.otpSended) {
      deb();
    }
  }, [telcoInfo?.otpSended]);

  const onSubmit = (e: any) => {
    e.preventDefault();
    if (!phoneHelperText && !telcoInfo.otpSended) {
      sendSMS();
    }
  };
  const onFurther = () => {
    pm.goForth({ blockUI: true });
  };

  const onBack = () => {
    pm.goBack(true);
  };

  return (
    <form onSubmit={onSubmit}>
      <Paper elevation={0} square={true} className={classes.paper}>
        <Grid container spacing={2}>
          <Grid item xl={12} lg={12} md={12} sm={12} xs={12}>
            <Typography variant="h6">
              <strong>Подписание согласия ОТР паролем</strong>
            </Typography>
          </Grid>

          <Grid item xl={7} lg={7} md={7} sm={6} xs={12}>
            <BccPhoneInputText
              disabled={telcoInfo?.otpSended || false}
              variant="filled"
              fullWidth
              style={{ height: "auto" }}
              value={telcoInfo?.phone || ""}
              onChangeValue={(value) => {
                onPhoneChange(value);

              }}
              label={"Номер телефона"}
              required
              helperText={phoneHelperText}
              error={!!phoneHelperText}
              inputProps={{
                pattern: "^[+][7]\\s[(]\\d{3}[)]\\s\\d{3}\\s\\d{2}\\s\\d{2}$",
                title: "Поле должно быть формата +7 (111) 111 11 11"
              }}
              onChangeProviderCode={(value) => {
                setPhoneHelperText(phoneProviderCheck(value, phoneProviders));
              }}
            />
          </Grid>
          <Grid item xl={5} lg={5} md={5} sm={6} xs={12}>
            <Grid container justify="flex-start">
              <BccButtonGreen
                disabled={telcoInfo?.otpSended || false}
                variant="contained"
                type="submit"
              >
                Отправить SMS клиенту
              </BccButtonGreen>
            </Grid>
          </Grid>

          <Grid item xl={7} lg={7} md={7} sm={12} xs={12}>
            <BccInputText
              disabled={telcoInfo?.otpSended || false}
              label="Язык обращения"
              fullWidth
              required
              variant="filled"
              value={telcoInfo?.language}
              select
              SelectProps={{ native: true }}
              onChange={(e: any) => {
                changeValue({
                  ...telcoInfo, language: e.target.value
                });
              }}
            >
              {languages.map((m) => (
                <option key={m.code} value={m.code}>
                  {m.value}
                </option>
              ))}
            </BccInputText>
          </Grid>
          <Grid item xl={7} lg={7} md={7} sm={12} xs={12}>
            <BccInputText
              disabled={telcoInfo?.otpSended || false}
              label="Тип документа"
              required
              fullWidth
              variant="filled"
              value={telcoInfo?.doctype}
              select
              SelectProps={{ native: true }}
              onChange={(e: any) => {
                changeValue({ ...telcoInfo, doctype: e.target.value });
              }}
            >
              {docTypes.filter(d => clientDoctypeList.includes(d.code!)).sort((a: any, b: any) => b.code.localeCompare(a.code))
                .map((m) => (
                  <option key={m.code} value={m.code}>
                    {m.name}
                  </option>
                ))}
            </BccInputText>
          </Grid>
        </Grid>

        <Grid container justify="flex-end" spacing={2}>
          <Grid item>
            <BccButtonRed onClick={() => onBack()}>
              Завершить
            </BccButtonRed>
          </Grid>
          <Grid item>
            <BccButtonGreen onClick={() => onFurther()}>Далее</BccButtonGreen>
          </Grid>
        </Grid>
      </Paper>
    </form>
  );
};

export default TelcoOTP;