import React, { useEffect, useState } from "react";
import { Button, Popover, TextField, Typography } from "@mui/material";
import axios from "axios";
import { RiSearchLine } from "react-icons/ri";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { Grid } from "../../../../components/grid/Grid";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { useDispatch } from "react-redux";
import { useParams } from "react-router-dom";
import { ProvinceAllocateStewardGuild } from "../province-allocate-steward-guild/ProvinceAllocateStewardGuild";
import { ProvinceCreateAllocateStewardGuild } from "../province-create-allocate-steward-guild/ProvinceCreateAllocateStewardGuild";

export const ProvinceDispensersView = ({ type, roleType }) => {
  const dispatch = useDispatch();
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const { key, name } = useParams();

  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) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `total-guilds-distribution-management/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}${
        roleType && "&role_type=" + roleType
      }${type && "&type=" + type}&key=${key}`
    );
    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 updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.guildsName,
        `${item?.user?.fullname} (${item?.user?.mobile})`,
        item?.city,
        item?.userLevel?.length
          ? item?.userLevel?.map((option, i) => (
              <Typography key={i} variant="body2">
                {option?.faTitle}
              </Typography>
            ))
          : "-",
        item?.typeActivity,
        item?.areaActivity,
        item?.generalInfos?.selfTotalAllocationType === "forced"
          ? "اجباری"
          : "اختیاری",
        item?.generalInfos?.inputTotalAllocationLimit?.toLocaleString(),
        item?.generalInfos?.outputTotalAllocationLimit?.toLocaleString(),
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `total-guilds-distribution-management/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&page=${1}&page_size=${perPage}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const [anchorEl, setAnchorEl] = React.useState(null);

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

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

  const open = Boolean(anchorEl);
  const id = open ? "simple-popover" : undefined;

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
        mt={2}
      >
        <Button
          aria-describedby={id}
          variant="contained"
          onClick={handleClick}
          sx={{
            backgroundColor: "#6200ea",
            fontSize: "16px",
            fontWeight: "500",
            textTransform: "none",
            "&:hover": {
              backgroundColor: "#3700b3",
            },
          }}
        >
          افزودن مباشر/ صنف به کشتارگاه
        </Button>

        <Popover
          id={id}
          open={open}
          anchorEl={anchorEl}
          onClose={handleClose}
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "right",
          }}
          transformOrigin={{
            vertical: "top",
            horizontal: "left",
          }}
          sx={{
            borderRadius: "12px",
            boxShadow: "0px 4px 20px rgba(0, 0, 0, 0.1)",
            "& .MuiPaper-root": {
              borderRadius: "12px",
              padding: "16px",
            },
          }}
        >
          <Grid
            container
            direction="column"
            spacing={2}
            sx={{ width: "240px" }}
          >
            <Grid item>
              <Button
                onClick={() => {
                  handleClose();
                  dispatch(
                    DRAWER({
                      right: !(window.innerWidth <= 600),
                      bottom: window.innerWidth <= 600,
                      title: "ایجاد و تخصیص مباشر/ صنف ",
                      content: (
                        <ProvinceCreateAllocateStewardGuild
                          updateTable={updateTable}
                          killHousekey={key}
                          type={"KillHouse"}
                        />
                      ),
                    })
                  );
                }}
                fullWidth
                variant="contained"
                sx={{
                  backgroundColor: "#6200ea",
                  color: "#ffffff",
                  borderRadius: "8px",
                  padding: "10px",
                  fontSize: "14px",
                  fontWeight: "500",
                  textTransform: "none",
                  "&:hover": {
                    backgroundColor: "#3700b3",
                  },
                }}
              >
                افزودن مباشر/ صنف
              </Button>
            </Grid>
            <Grid item>
              <Button
                onClick={() => {
                  handleClose();
                  dispatch(
                    OPEN_MODAL({
                      title: "تخصیص مباشر/ صنف ",
                      content: (
                        <ProvinceAllocateStewardGuild
                          updateTable={updateTable}
                          killHousekey={key}
                          type={"KillHouse"}
                        />
                      ),
                    })
                  );
                }}
                fullWidth
                variant="outlined"
                sx={{
                  borderColor: "#6200ea",
                  color: "#6200ea",
                  borderRadius: "8px",
                  padding: "10px",
                  fontSize: "14px",
                  fontWeight: "500",
                  textTransform: "none",
                  "&:hover": {
                    borderColor: "#3700b3",
                    backgroundColor: "rgba(98, 0, 234, 0.08)",
                  },
                }}
              >
                انتخاب مباشر/ صنف
              </Button>
            </Grid>
          </Grid>
        </Popover>

        <Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
        </Grid>
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "نام واحد",
          "کاربر",
          "شهر",
          "سطح فعالیت",
          "نوع فعالیت",
          "حوزه فعالیت",
          "نوع تعهد",
          "وزن تعهد دریافتی",
          "وزن تعهد تخصیصی",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title={
          type === "steward"
            ? `مباشرین ${roleType === "KillHouse" && "کشتارگاه "} ${name}`
            : `اصناف ${roleType === "KillHouse" && "کشتارگاه "} ${name}`
        }
      />
    </Grid>
  );
};
