import React, { useState } from "react";
import IconButton from "../../components/IconButton/IconButton";
import planeVector from "../../assets/images/planeVector.png";
import lock from "../../assets/images/lock.png";
// import filters from "../../assets/images/filters.png";
import forbiden from "../../assets/images/forbiden.png";
import x from "../../assets/images/x.png";
import edit from "../../assets/images/edit.png";
import { useEffect } from "react";
import addUser from "../../assets/images/addUser.png";
// import { getAllUsers } from "../../request/usersRequest";
// import { getUsers } from "../../store/saga/usersSaga";
import { useDispatch, useSelector } from "react-redux";
import {
  // deleteUserReq,
  setEnableUsersReq,
  setUsersReq,
} from "../../store/actions/users/usersActions";
import { useTheme } from "@mui/system";
import { TextField, useMediaQuery } from "@mui/material";
// import DialogComponent from "../../components/MUI/DialogComponent";
import InviteDialog from "../../components/MUI/InviteDialog";
import { Link } from "react-router-dom";
import { forgetPassword } from "../../store/actions/login/loginActions";
import { useTranslation } from "react-i18next";
import ConfirmDialog from "../../components/MUI/ConfirmDialog";
import EditButton from "../../components/Button/EditButton";

const UsersPage = () => {
  const theme = useTheme();
  const matches = useMediaQuery(theme.breakpoints.down("sm"));
  const dispatch = useDispatch();
  const { users } = useSelector((s) => s.users);

  const [showInvite, setShowInvite] = useState(false);
  const [editEnable, setEdit] = useState(false);
  const [search, setSearch] = useState("");
  const [chosen, setChosen] = useState(null);
  const [showConfirm, setConfirm] = useState(false);
  const [showReset, setReset] = useState(false);

  const { t } = useTranslation();

  useEffect(() => {
    dispatch(setUsersReq());
  }, [dispatch]);

  const disableHandler = (id) => {
    dispatch(
      setEnableUsersReq({
        id,
        handleApiResponseSuccess: handleApiResponseSuccessEnable,
      })
    );
  };

  const handleReset = (email) => {
    dispatch(
      forgetPassword({
        email,
        handleApiResponseSuccess: handleApiResponseSuccessReset,
      })
    );
  };

  const handleApiResponseSuccessReset = () => {
    setReset(false);
  };

  const handleApiResponseSuccessEnable = () => {
    setConfirm(false);
  };
  const formatLabel = (string, value) => {
    if (!value) {
      return string;
    }
    return (
      <span>
        {string.split(value).reduce((prev, current, i) => {
          if (!i) {
            return [current];
          }
          return prev.concat(
            <b className="highlighted" key={value + current}>
              {value}
            </b>,
            current
          );
        }, [])}
      </span>
    );
  };

  return (
    <div>
      <div className="l-t-rectangle"></div>
      <div className="r-b-rectangle"></div>
      <ConfirmDialog
        open={showConfirm}
        title={"Disable user"}
        subtitle={chosen?.firstName + " " + chosen?.lastName}
        imgSrc={forbiden}
        content="Are you sure you want to disable user?"
        onClose={() => {
          setConfirm(false);
        }}
        onConfirm={() => {
          disableHandler(chosen.id);
          // setConfirm(false)
        }}
      />
      <ConfirmDialog
        open={showReset}
        title={"Reset password"}
        subtitle={chosen?.firstName + " " + chosen?.lastName}
        imgSrc={lock}
        content="Are you sure you want to send password reset link?"
        onClose={() => {
          setReset(false);
        }}
        onConfirm={() => {
          handleReset(chosen.email);
          // setConfirm(false)
        }}
      />
      <InviteDialog
        open={showInvite}
        onClose={() => {
          setShowInvite(false);
        }}
        title={
          <div
            className="flex-center"
            style={{ justifyContent: "space-between" }}
          >
            <div className="flex-center" style={{ justifyContent: "start" }}>
              <img
                style={{
                  position: "relative",
                  top: -0.25,
                  paddingRight: "10px",
                }}
                src={addUser}
              />
              <h5>{t("users.inviteUser")}</h5>
              {!matches && <div className="vr"></div>}
              {!matches && <p className="dialog-subtitle">{t("users.regLink")}</p>}
            </div>
            <IconButton onClick={() => setShowInvite(false)}>
              <img
                style={{
                  position: "relative",
                  top: -0.25,
                }}
                src={x}
              />
            </IconButton>
          </div>
        }
      />
      <div>
        <div
          className="pl-144 flex-center"
          style={{ paddingTop: "36px", justifyContent: "space-between" }}
        >
          <h1 className="page-heading">{t("users.management")}</h1>
          <div className="flex-center">
            {/* <button></button> */}
            <EditButton
              onEnableEdit={() => {
                setEdit((s) => !s);
              }}
            />
            <IconButton
              className={"c-btn--primary c-btn inviteBtn"}
              onClick={() => {
                setShowInvite(true);
              }}
            >
              {t("users.invite")}
              <img
                style={{
                  position: "relative",
                  top: 1.25,
                  paddingLeft: "15px",
                }}
                src={planeVector}
              />{" "}
            </IconButton>
          </div>
        </div>
        <div
          className="pl-144"
          style={{
            display: "flex",
            marginTop: "39px",
            flexDirection: "column",
            justifyContent: "space-between",
            minHeight: "500px",
          }}
        >
          <div className="table-cont">
            <TextField
              name="username"
              label={t("common.labelUsername")}
              margin="normal"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              style={{
                width: editEnable ? "960px" : '720px',
              }}
            />
            <table className={editEnable ? 'usersTable-users normal' : 'usersTable-users mini'} 
            // style={{ width: "893.56px" }}
            >
              <thead>
                <tr className="headingRow">
                  <th>{t("users.fullName")}</th>
                  <th>E-mail</th>
                  <th>{t("users.position")}</th>
                  {editEnable && <th></th>}
                </tr>
              </thead>
              <tbody>
                {
                  users
                    .filter((n) =>
                      (n.firstName + " " + n.lastName)
                        .toLowerCase()
                        .includes(search.toLowerCase())
                    )
                    .map((n) => (
                      <tr key={n.id} className="secondaryRow">
                        <td>
                          {(n.firstName + " " + n.lastName).includes(search) ? (
                            formatLabel(n.firstName + " " + n.lastName, search)
                          ) : (
                            <span>{n.firstName + " " + n.lastName}</span>
                          )}
                        </td>
                        <td>{n.email}</td>
                        <td className='profession'>{n.position}</td>
                        {editEnable && (
                          <td>
                            <>
                              <IconButton
                                className={`c-btn--primary-outlined c-btn td-btn`}
                                onClick={() => {
                                  setChosen(n);
                                  setReset(true);
                                }}
                              >
                                <img
                                  style={{
                                    position: "relative",
                                  }}
                                  src={lock}
                                />
                              </IconButton>
                              <IconButton
                                className={`c-btn--primary-outlined c-btn td-btn ${
                                  n.isEnabled ? "active" : "inactive"
                                }`}
                                onClick={() => {
                                  setChosen(n);
                                  setConfirm(true);
                                }}
                              >
                                <img
                                  style={{
                                    position: "relative",
                                  }}
                                  src={forbiden}
                                />
                              </IconButton>
                              <Link to={`/users/${n.id}`}>
                                <IconButton
                                  className={
                                    "c-btn--primary-outlined c-btn td-btn"
                                  }
                                >
                                  <img
                                    style={{
                                      position: "relative",
                                    }}
                                    src={edit}
                                  />
                                </IconButton>
                              </Link>
                            </>
                          </td>
                        )}
                      </tr>
                    ))
                }
              </tbody>
            </table>
          </div>
          <div
            style={{
              display: "flex",
              justifyContent: "flex-end",
              marginBottom: "35px",
            }}
          ></div>
        </div>
      </div>
    </div>
  );
};

export default UsersPage;
