import { Button, TextField, Tooltip, Typography } from "@mui/material";
import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { SelectCheck } from "../../../../components/select-check/SelectCheck";
import { ROLES } from "../../../../data/roles";
import { SPACING } from "../../../../data/spacing";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { useFormik } from "formik";
import * as Yup from "yup";
import { useDispatch } from "react-redux";
import { provinceGetUsersByRolesService } from "../../services/province-get-users-by-roles";
import { provinceSendSmsService } from "../../services/province-send-sms";
import { AppContext } from "../../../../contexts/AppContext";
import AddIcon from "@mui/icons-material/Add";
import RefreshIcon from "@mui/icons-material/Refresh";
import { RiFileExcel2Fill } from "react-icons/ri";
import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable";

export function ProvinceSmsComponent() {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const [provinceGetUsersByRoles, setProvinceGetUsersByRoles] = useState([]);
  const [usersForSelect, setUsersForSelect] = useState([]);
  const [selectedUsers, setSelectedUsers] = useState([]);

  useEffect(() => {
    if (provinceGetUsersByRoles.length) {
      const d = provinceGetUsersByRoles.map((item) => {
        return { label: item.fullname, value: item.key };
      });
      setUsersForSelect(d);
    }
  }, [provinceGetUsersByRoles]);

  const [rolesForSelect] = useState(
    ROLES.map((role, i) => ({
      label: getFaUserRole(role),
      value: role,
    }))
  );

  const validationSchema = Yup.object().shape({
    selectedRoles: Yup.array().required("لطفا نقش را انتخاب کنید"),
    inputText: Yup.string().required("لطفا متن پیامک را وارد کنید"),
  });

  const onSubmit = () => {
    dispatch(
      provinceSendSmsService({
        user: selectedUsers,
        message: formik.values.inputText,
        role: formik.values.selectedRoles,
      })
    ).then((r) => {
      if (r.payload.status === 200) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  };

  const formik = useFormik({
    initialValues: {
      selectedRoles: [],
      inputText: "",
    },
    validationSchema,
    onSubmit,
  });

  useEffect(() => {
    formik.validateForm();
  }, []);

  const handleCalculatePrice = (message) => {
    const isPersianMessage = /[آ-ی]/.test(message);

    let price = 0;

    if (isPersianMessage) {
      price = handleCountMessages(message) * 980;
    } else {
      price = handleCountMessages(message) * 1320;
    }

    if (formik.values.selectedRoles.length) {
      if (selectedUsers.length > 0) {
        return price * selectedUsers.length + " ریال";
      } else {
        return price * usersForSelect.length + " ریال";
      }
    } else {
      return "نامشخص (پیامک برای کل کاربران ارسال میشود) ";
    }
  };

  const handleCountMessages = (message) => {
    const charCountPerLatinPage = [160, 146, 153, 153];
    const charCountPerPersianPage = [70, 64, 67, 67];

    const isPersianMessage = /[آ-ی]/.test(message);

    const charCountPerPage = isPersianMessage
      ? charCountPerPersianPage
      : charCountPerLatinPage;

    let totalChars = message.length;
    let pageCount = 0;

    while (totalChars > 0) {
      const charCountOnCurrentPage =
        charCountPerPage[pageCount] ||
        charCountPerPage[charCountPerPage.length - 1];

      if (totalChars >= charCountOnCurrentPage) {
        totalChars -= charCountOnCurrentPage;
        pageCount++;
      } else {
        pageCount++;
        break;
      }
    }

    return pageCount;
  };

  useEffect(() => {
    if (formik.values.selectedRoles.length) {
      dispatch(
        provinceGetUsersByRolesService({
          role: formik.values.selectedRoles.join(","),
        })
      ).then((r) => setProvinceGetUsersByRoles(r.payload.data));
    }
  }, [formik.values.selectedRoles]);

  return (
    <Grid container mx={SPACING.SMALL} justifyContent="space-between">
      <Grid
        item
        xs={12}
        sm={12}
        md={4}
        lg={3}
        direction="column"
        alignItems="start"
        gap={SPACING.SMALL}
      >
        <Grid>
          <form
            style={{
              display: "flex",
              alignItems: "start",
              flexDirection: "column",
              gap: SPACING.LARGE,
            }}
            onSubmit={formik.handleSubmit}
          >
            <Grid>
              <SelectCheck
                name="selectedOption"
                label={"انتخاب نقش"}
                onChange={(e) => formik.setFieldValue("selectedRoles", e)}
                options={rolesForSelect}
              />

              {formik.errors.selectedOption && (
                <Typography
                  variant="caption"
                  color={(prop) => prop.palette.grey["A700"]}
                >
                  {formik.errors.selectedOption}
                </Typography>
              )}
            </Grid>

            {!!usersForSelect.length && (
              <Grid container direction="column" alignItems="start">
                <Grid>
                  <SelectCheck
                    name="slaughterHousesListForSelect"
                    label={"انتخاب کاربر"}
                    onChange={(e) => setSelectedUsers(e)}
                    options={usersForSelect}
                  />
                </Grid>

                <Grid container gap={SPACING.TINY} mt={SPACING.SMALL}>
                  <Grid item>
                    <Typography variant="button" color={"red"}>
                      تعداد کاربر انتخابی:
                    </Typography>
                  </Grid>
                  <Grid item mb={SPACING.SMALL}>
                    <Typography
                      variant="caption"
                      color={(prop) => prop.palette.grey["A700"]}
                    >
                      {selectedUsers.length > 0 ? selectedUsers.length : "همه"}
                    </Typography>
                  </Grid>
                </Grid>
              </Grid>
            )}

            <Grid container>
              <Grid container direction="column" alignItems="start">
                <Grid>
                  <TextField
                    style={{ width: "280px" }}
                    id="inputText"
                    name="inputText"
                    label="متن پیامک را وارد کنید"
                    multiline
                    rows={10}
                    value={formik.values.inputText}
                    onChange={formik.handleChange}
                  />
                </Grid>
                {formik.errors.inputText && (
                  <Typography
                    mt={SPACING.TINY}
                    variant="caption"
                    color={(prop) => prop.palette.grey["A700"]}
                  >
                    {formik.errors.inputText}
                  </Typography>
                )}
                <Grid
                  container
                  direction="row"
                  alignItems="start"
                  gap={SPACING.LARGE}
                >
                  <Grid container gap={SPACING.TINY}>
                    <Grid item>
                      <Typography variant="button" color={"red"}>
                        تعداد کاراکتر:
                      </Typography>
                    </Grid>
                    <Grid item mb={SPACING.SMALL}>
                      <Typography
                        variant="caption"
                        color={(prop) => prop.palette.grey["A700"]}
                      >
                        {formik.values.inputText.length}
                      </Typography>
                    </Grid>
                  </Grid>

                  <Grid container gap={SPACING.TINY}>
                    <Grid item>
                      <Typography variant="button" color={"red"}>
                        تعداد پیامک:
                      </Typography>
                    </Grid>
                    <Grid item mb={SPACING.SMALL}>
                      <Typography
                        variant="caption"
                        color={(prop) => prop.palette.grey["A700"]}
                      >
                        {handleCountMessages(formik.values.inputText)}
                      </Typography>
                    </Grid>
                  </Grid>
                </Grid>
                <Grid>
                  <Tooltip
                    title={
                      "در صورتی که کاربری انتخاب نکنید پیغام برای همه کاربران نقش ارسال میشود"
                    }
                    placement="left"
                  >
                    <Button
                      disabled={!formik.isValid}
                      variant="contained"
                      type="submit"
                    >
                      ارسال پیامک
                    </Button>
                  </Tooltip>
                </Grid>
              </Grid>
            </Grid>
          </form>
        </Grid>
      </Grid>
      <Grid
        item
        container
        direction="column"
        alignItems="start"
        gap={SPACING.SMALL}
        xs={12}
        sm={12}
        md={7}
        lg={8}
      >
        <Grid
          container
          xs={12}
          sm={12}
          md={12}
          lg={12}
          gap="20px"
          alignItems="center"
          justifyContent="start"
        >
          <Grid>
            <Typography
              sx={{ marginRight: "5px" }}
              variant="v2"
              color={"green"}
            >
              مانده حساب:
            </Typography>
            <Typography
              variant="caption"
              color={(prop) => prop.palette.grey["A700"]}
            >
              230,000 ریال
            </Typography>
          </Grid>
          <Grid>
            <Typography sx={{ marginRight: "5px" }} variant="v2" color={"red"}>
              محاسبه تقریبی هزینه پیام:
            </Typography>
            <Typography
              variant="caption"
              color={(prop) => prop.palette.grey["A700"]}
            >
              {handleCalculatePrice(formik.values.inputText).toLocaleString()}{" "}
            </Typography>
          </Grid>
          <Grid
            xs={12}
            sm={12}
            md={12}
            container
            justifyContent="space-between"
          >
            <Grid container justifyContent="start" gap={SPACING.TINY}>
              <Button
                component="a"
                href="http://sahandsms.com/OnlineCharge/OnlineCharge.aspx"
                target="_blank"
                startIcon={<AddIcon />}
                variant="contained"
                size="small"
                type="submit"
              >
                شارژ کیف پول
              </Button>

              <Button
                component="a"
                href="http://sahandsms.com/OnlineCharge/OnlineCharge.aspx"
                startIcon={<RiFileExcel2Fill />}
                variant="contained"
                size="small"
                type="submit"
                color="success"
              >
                خروجی اکسل
              </Button>
            </Grid>
            <Grid>
              <Button
                startIcon={<RefreshIcon />}
                variant="contained"
                size="small"
                type="submit"
                color="success"
              >
                بروزرسانی پیام ها
              </Button>
            </Grid>
          </Grid>
        </Grid>
        <AdvancedTable
          name="پیام های ارسال شده"
          columns={[
            "نقش",
            "نام و نام خانوادگی",
            "تلفن",
            "متن پیام",
            "تاریخ ارسال",
            "وضعیت",
          ]}
        />
      </Grid>
    </Grid>
  );
}
