import React, { useContext, useEffect, useState } from "react";
import {
  Button,
  IconButton,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { AppContext } from "../../../../contexts/AppContext";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { useNavigate } from "react-router-dom";
import { SET_ADMIN_TOKEN } from "../../../../lib/redux/slices/userSlice";
import VpnKeyIcon from "@mui/icons-material/VpnKey";
import { loginWithPassword } from "../../../authentication/services/login";
import ContactPageIcon from "@mui/icons-material/ContactPage";
import TuneIcon from "@mui/icons-material/Tune";
import {
  ROUTE_ADMINX_OPERATOR_USER_FILE,
  ROUTE_PROVINCE_USER_FILE,
  ROUTE_SUPER_ADMIN_OPERATOR_USER_FILE,
} from "../../../../routes/routes";
import { ProvinceSubmitUser } from "../../../province/components/province-submit-user/ProvinceSubmitUser";
import { RiFileExcel2Fill } from "react-icons/ri";
import { SPACING } from "../../../../data/spacing";
import { SelectCheck } from "../../../../components/select-check/SelectCheck";
import { RiSearchLine } from "react-icons/ri";

export const UserPagination = () => {
  const navigate = useNavigate();
  const authToken = useSelector((state) => state.userSlice.authToken);

  useContext(AppContext);
  const dispatch = useDispatch();

  const UserActions = ({ item }) => {
    const [anchorEl, setAnchorEl] = useState(null);
    const open = Boolean(anchorEl);

    const handleOpen = (event) => {
      setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
      setAnchorEl(null);
    };

    const handleNavigateToFile = () => {
      navigate(
        getRoleFromUrl() === "AdminX"
          ? ROUTE_ADMINX_OPERATOR_USER_FILE + item?.key
          : getRoleFromUrl() === "SuperAdmin"
          ? ROUTE_SUPER_ADMIN_OPERATOR_USER_FILE + item?.key
          : getRoleFromUrl() === "ProvinceOperator"
          ? ROUTE_PROVINCE_USER_FILE + item?.key
          : ROUTE_PROVINCE_USER_FILE + item?.key
      );
      handleClose();
    };

    const handleLoginToPanel = () => {
      dispatch(SET_ADMIN_TOKEN(authToken));
      dispatch(LOADING_START());
      dispatch(
        loginWithPassword({
          mobile: item?.mobile,
          password: item?.password,
        })
      ).then(() => {
        dispatch(LOADING_END());
        navigate("/");
      });
      handleClose();
    };

    const canLogin =
      getRoleFromUrl() === "AdminX" || getRoleFromUrl() === "SuperAdmin";

    return (
      <Grid>
        <Tooltip title={"تنظیمات"} placement="right-start">
          <IconButton
            aria-label="actions"
            color="primary"
            className="avicultureActiveRequestsBtn"
            onClick={handleOpen}
          >
            <TuneIcon />
          </IconButton>
        </Tooltip>
        <Popover
          open={open}
          anchorEl={anchorEl}
          onClose={handleClose}
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "right",
          }}
          transformOrigin={{
            vertical: "top",
            horizontal: "left",
          }}
        >
          <List sx={{ minWidth: 200, p: 1 }}>
            <ListItemButton onClick={handleNavigateToFile}>
              <ListItemIcon>
                <ContactPageIcon fontSize="small" color="primary" />
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography variant="body2" sx={{ color: "primary.main" }}>
                    پرونده کاربر
                  </Typography>
                }
              />
            </ListItemButton>
            {canLogin && (
              <ListItemButton onClick={handleLoginToPanel}>
                <ListItemIcon>
                  <VpnKeyIcon fontSize="small" color="success" />
                </ListItemIcon>
                <ListItemText
                  primary={
                    <Typography variant="body2" sx={{ color: "success.main" }}>
                      ورود به پنل
                    </Typography>
                  }
                />
              </ListItemButton>
            )}
          </List>
        </Popover>
      </Grid>
    );
  };
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const [rolesSelected, setRolesSelected] = useState([]);
  const rolesQueryParam = rolesSelected.length ? rolesSelected.join() : "";

  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [tableData, setTableData] = useState([]);

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `system_user_profile/?users_info&search=filter&value=${
        textValue || ""
      }&page=${page}&page_size=${perPage}&roles=${rolesQueryParam}`
    );
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };

  const getPassword = (item) => {
    if (getRoleFromUrl() !== "ProvinceOperator") {
      return [item?.password];
    } else {
      return [];
    }
  };
  const getPasswordColumn = () => {
    if (getRoleFromUrl() !== "ProvinceOperator") {
      return ["کلمه عبور"];
    } else {
      return [];
    }
  };

  //   const updateTable = () => {
  //     fetchApiData(page !== 0 ? page : 1);
  //   };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.fullname
          ? item?.fullname
          : item?.firstName + " " + item?.lastName,
        <Grid key={i}>
          {!(item?.role?.length > 0) && "کاربر پایه"}
          {item?.role?.map((item, i) => {
            let name = "";
            switch (item) {
              case "ProvinceOperator":
                name = "اپراتور تخصیص استان";
                break;
              case "CityOperator":
                name = "اپراتور شهرستان";
                break;
              case "KillHouseVet":
                name = "دامپزشک کشتارگاه";
                break;
              case "VetFarm":
                name = "دامپزشک";
                break;
              case "Poultry":
                name = "مرغدار";
                break;
              case "KillHouse":
                name = "کشتارگاه";
                break;
              case "Vet":
                name = "دامپزشک";
                break;
              case "ProvinceInspector":
                name = "بازرس استان";
                break;
              case "ProvinceFinancial":
                name = "اپراتور مالی";
                break;
              case "Driver":
                name = "راننده";
                break;
              case "Admin":
                name = "ادمین";
                break;

              default:
                break;
            }
            return <Grid key={i}>{name}</Grid>;
          })}
        </Grid>,
        item?.mobile,
        item?.baseOrder,
        item?.city,
        ...getPassword(item),
        <UserActions key={i} item={item} />,
      ];
    });

    setTableData(d);
  }, [data]);

  useEffect(() => {
    fetchApiData(1);
  }, [dispatch, perPage]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `system_user_profile/?users_info&search=filter&value=${
          textValue || ""
        }&page=${page}&page_size=${perPage}&roles=${rolesQueryParam}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        alignItems="center"
        mb={SPACING.SMALL}
        gap={SPACING.SMALL}
      >
        <Typography>کاربران</Typography>
        <Button
          className="first-step"
          variant={"contained"}
          onClick={() => {
            dispatch(
              DRAWER({
                title: "ثبت کاربر جدید",
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content: <ProvinceSubmitUser />,
              })
            );
          }}
        >
          ثبت کاربر جدید
        </Button>
        <SelectCheck
          size="small"
          label={"فیلتر نقش"}
          onChange={(e) => setRolesSelected(e)}
          options={[
            { label: "اپراتور تخصیص استان", value: "ProvinceOperator" },
            { label: "اپراتور شهرستان", value: "CityOperator" },
            { label: "بازرس استان", value: "ProvinceInspector" },
            { label: "دامپزشک", value: "VetFarm" },
            { label: "کشتارگاه", value: "KillHouse" },
            { label: "دامپزشک کشتارگاه", value: "KillHouseVet" },
            { label: "مرغدار", value: "Poultry" },
            { label: "اپراتور مالی", value: "ProvinceFinancial" },
            { label: "راننده", value: "Driver" },
            { label: "ادمین", value: "Admin" },
          ]}
        />

        <form onSubmit={handleSubmit}>
          <Grid container alignItems="center" gap={SPACING.SMALL}>
            <TextField
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </Grid>
        </form>
        <Grid>
          <Tooltip title="خروجی اکسل">
            <a
              href={`${axios.defaults.baseURL}get_all_user_excel/`}
              rel="noreferrer"
            >
              <Button color="success">
                <RiFileExcel2Fill size={32} />
              </Button>
            </a>
          </Tooltip>
        </Grid>
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "نام کامل",
          "نوع کاربری",
          "شماره تلفن",
          "کد کاربری",
          "شهر",
          ...getPasswordColumn(),
          "عملیات",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="مدیریت کاربران"
      />
    </Grid>
  );
};
