import React, { useContext, useEffect, useState } from "react";
import {
  Button,
  IconButton,
  Popover,
  TextField,
  Tooltip,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Typography,
} from "@mui/material";
import TuneIcon from "@mui/icons-material/Tune";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";
import ToggleOffIcon from "@mui/icons-material/ToggleOff";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { ProvinceFreeSaleAddBuyer } from "../province-free-sale-add-buyer/ProvinceFreeSaleAddBuyer";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { SPACING } from "../../../../data/spacing";
import EditIcon from "@mui/icons-material/Edit";
import { provinceFreeSalesEditBuyer } from "../../services/province-free-sales-edit-buyer";
import { AppContext } from "../../../../contexts/AppContext";

const BuyerOperations = ({ item, fetchApiData, openNotif }) => {
  const dispatch = useDispatch();
  const [anchorEl, setAnchorEl] = useState(null);

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

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

  const handleToggleActive = () => {
    handleClose();
    dispatch(
      provinceFreeSalesEditBuyer({
        buyer_key: item?.key,
        active: !item?.active,
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        fetchApiData(1);
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  };

  const handleEdit = () => {
    handleClose();
    dispatch(
      DRAWER({
        right: !(window.innerWidth <= 600),
        bottom: window.innerWidth <= 600,
        title: "ویرایش خریدار",
        content: (
          <ProvinceFreeSaleAddBuyer
            fetchApiData={fetchApiData}
            isEdit
            item={item}
          />
        ),
      })
    );
  };

  const options = [
    {
      key: "toggle",
      label: item?.active ? "غیرفعال سازی" : "فعالسازی",
      color: item?.active ? "error.main" : "success.main",
      icon: item?.active ? <ToggleOffIcon /> : <ToggleOnIcon />,
      action: handleToggleActive,
    },
    {
      key: "edit",
      label: "ویرایش",
      color: "primary.main",
      icon: <EditIcon />,
      action: handleEdit,
      disabled: !item?.active,
    },
  ];

  const open = Boolean(anchorEl);
  const id = open ? `buyer-operations-${item?.key}` : undefined;

  return (
    <Grid container alignItems="center" justifyContent="center" gap={0.5}>
      <Tooltip title="تنظیمات">
        <IconButton aria-describedby={id} color="primary" onClick={handleOpen}>
          <TuneIcon />
        </IconButton>
      </Tooltip>
      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <List dense sx={{ width: 150, py: 0.5, px: 1 }}>
          {options.map((option) => (
            <ListItemButton
              key={option.key}
              onClick={() => {
                if (option.disabled) {
                  return;
                }
                option.action();
              }}
              disabled={Boolean(option.disabled)}
              sx={{
                borderRadius: 1,
                mb: 0.5,
                color: option.disabled ? "text.disabled" : option.color,
                "&:last-of-type": {
                  mb: 0,
                },
              }}
            >
              <ListItemIcon
                sx={{
                  color: option.disabled ? "text.disabled" : option.color,
                  minWidth: 32,
                }}
              >
                {React.cloneElement(option.icon, { fontSize: "small" })}
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography
                    sx={{
                      color: option.disabled ? "text.disabled" : option.color,
                      fontWeight: 600,
                      fontSize: "0.85rem",
                    }}
                  >
                    {option.label}
                  </Typography>
                }
              />
            </ListItemButton>
          ))}
        </List>
      </Popover>
    </Grid>
  );
};

export const ProvinceFreeSalsesManageBuyers = () => {
  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 dispatch = useDispatch();

  const [openNotif] = useContext(AppContext);

  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `out-province-poultry-request-buyers/?search=filter&value=${textValue}&page=${page}&page_size=${perPage}&role=${getRoleFromUrl()}&state=buyer-list`
    );

    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);
  };

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.fullname,
        item?.mobile,
        item?.province,
        item?.city,
        item?.type === "killhouse" ? "کشتارگاه" : "کشتارکن",
        item?.unitName ? item?.unitName : "-",
        item?.killHouseUniqueId ? item?.killHouseUniqueId : "-",
        item?.requestsInfo?.numberOfRequests?.toLocaleString(),
        item?.requestsInfo?.totalQuantity?.toLocaleString(),
        item?.requestsInfo?.totalWeight?.toLocaleString(),
        item?.active ? "فعال" : "غیر فعال",
        <BuyerOperations
          key={item?.key || i}
          item={item}
          fetchApiData={fetchApiData}
          openNotif={openNotif}
        />,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `out-province-poultry-request-buyers/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&state=buyer-list`
      );

      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 mt={SPACING.SMALL} xs={12}>
        <Button
          variant="contained"
          onClick={() => {
            dispatch(
              DRAWER({
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                title: "افزودن خریدار",
                content: (
                  <ProvinceFreeSaleAddBuyer fetchApiData={updateTable} />
                ),
              })
            );
          }}
        >
          افزودن خریدار
        </Button>
      </Grid>
      <Grid
        container
        alignItems="center"
        justifyContent="center"
        gap={2}
        paddingTop={2}
        mb={1}
        width="100%"
      >
        <Grid container alignItems="center" gap={SPACING.SMALL}>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
        </Grid>
        <Tooltip title="خروجی اکسل">
          <a
            href={`${
              axios.defaults.baseURL
            }out_province_poultry_request_buyers_excel/?key=${userKey}&role=${getRoleFromUrl()}&search=filter&value=${textValue}`}
            rel="noreferrer"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "نام کامل",
          "موبایل",
          "استان",
          "شهر",
          "ماهیت خریدار",
          "نام واحد",
          "شناسه یکتا",
          "تعداد درخواست ها",
          "حجم درخواست ها (قطعه)",
          "وزن درخواست ها (کیلوگرم)",
          "وضعیت",
          "عملیات",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="خریداران"
      />
    </Grid>
  );
};
