import { Button, Tooltip, MenuItem, TextField } from "@mui/material";
import axios from "axios";
import { useEffect, useState } from "react";
import { RiFileExcel2Fill } from "react-icons/ri";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { provinceGetStewardsService } from "../../services/province-get-stewards";
import { ManageStewardsOperations } from "../manage-stewards-operations/ManageStewardsOperations";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";

export const ManageStewards = () => {
  const dispatch = useDispatch();
  const [dataTable, setDataTable] = useState([]);
  const [statusFilter, setStatusFilter] = useState("همه");
  const { provinceGetStewards } = useSelector((state) => state.provinceSlice);
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

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

  useEffect(() => {
    const filtered =
      statusFilter === "همه"
        ? provinceGetStewards
        : provinceGetStewards?.filter((item) =>
            statusFilter === "فعال" ? item?.active : !item?.active
          );

    const d = filtered?.map((item, i) => {
      const dataRow = [
        i + 1,
        item?.guilds?.guildsId,
        item?.guilds?.guildsName,
        `${item?.guilds?.user?.fullname} (${item?.guilds?.user?.mobile})`,
        item?.guilds?.user?.nationalId,
        item?.guilds?.typeActivity,
        item?.guilds?.areaActivity,
        item?.guilds?.licenseNumber,
        `${item?.guilds?.address?.province.name}/${item?.guilds?.address?.city.name}`,
        item?.guilds?.address?.address,
        item?.limitationAllocation ? "دارد" : "ندارد",
        item?.allocationLimit?.toLocaleString(),
        item?.centersAllocation?.map((item) => item.label).join(" - "),
        item?.productInfo?.totalCarcassesWeight?.toLocaleString(),
        item?.productInfo?.realAllocatedWeight?.toLocaleString(),
        <ManageStewardsOperations guild={item} key={i} />,
      ];

      if (getRoleFromUrl() === "CityJahad") {
        dataRow.pop();
      }
      return dataRow;
    });

    setDataTable(d);
  }, [provinceGetStewards, statusFilter]);

  const columns = [
    "ردیف",
    "شناسه صنف",
    "نام واحد صنفی",
    "نام شخص/شرکت",
    "کدملی",
    "نوع فعالیت",
    "حوزه فعالیت",
    "شماره مجوز",
    "استان/شهرستان",
    "آدرس واحد صنفی",
    "محدودیت تخصیص",
    "حداکثر تخصیص",
    "مراکز تخصیص",
    "وزن خرید (کیلوگرم)",
    "وزن فروش (کیلوگرم)",
    "عملیات",
  ];

  if (getRoleFromUrl() === "CityJahad") {
    columns.pop();
  }

  return (
    <Grid container>
      <Grid container alignItems="center" gap={SPACING.SMALL}>
        <Tooltip title="خروجی اکسل">
          <a
            href={`${
              axios.defaults.baseURL
            }stewards_excel/?role=${getRoleFromUrl()}&key=${userKey}`}
            rel="noreferrer"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>

        <TextField
          select
          label="وضعیت"
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          size="small"
          sx={{ width: 150 }}
        >
          <MenuItem value="همه">همه</MenuItem>
          <MenuItem value="فعال">فعال</MenuItem>
          <MenuItem value="غیرفعال">غیرفعال</MenuItem>
        </TextField>
      </Grid>

      <ResponsiveTable
        title="مباشرین"
        paginated
        columns={columns}
        data={dataTable}
      />
    </Grid>
  );
};
