import React, { useEffect, useState } from "react";
import { Button, TextField, Tooltip, MenuItem } from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { provinceGetTotalGuildsService } from "../../services/province-get-total-guilds";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { ManageGuildsOperations } from "../manage-guilds-operations/ManageGuildsOperations";
import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { SPACING } from "../../../../data/spacing";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { CreateGuilds } from "../create-guilds/CreateGuilds";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const MaangeGuilds = () => {
  const userKey = useSelector((state) => state.userSlice?.userProfile?.key);
  const dispatch = useDispatch();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  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 [activeState, setActiveState] = useState("active");

  const handleTextChange = (e) => setTextValue(e.target.value);
  // const handleCheckboxChange = () => setIsSteward(!isSteward);

  const fetchApiData = async (page) => {
    const response = await dispatch(
      provinceGetTotalGuildsService({
        search: "filter",
        value: textValue,
        page: page,
        page_size: perPage,
        steward: false,
        active_state: activeState,
        is_real_person: true,
        role_key: checkPathStartsWith("province")
          ? selectedSubUser?.key || ""
          : "",
      })
    );

    if (response.payload.error) {
      console.error("Error fetching data:", response.payload.error);
      setData([]);
      setTotalRows(0);
    } else {
      setData(response.payload.data?.results || []);
      setTotalRows(response.payload.data?.count || 0);
    }
  };

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

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

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

  useEffect(() => {
    fetchApiData(1);
  }, [perPage, selectedSubUser?.key, activeState]);

  useEffect(() => {
    if (!data || !Array.isArray(data)) {
      setTableData([]);
      return;
    }
    const d = data.map((item, i) => {
      const commonData = [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.licenseNumber || "-",
        item?.guildsName || "-",
        `${item?.user?.fullname || "-"} (${item?.user?.mobile || "-"})`,
        item?.user?.nationalId ? item?.user?.nationalId : "-",
        item?.typeActivity || "-",
        item?.areaActivity || "-",
        item?.address?.postalCode || "-",
        `${item?.address?.province?.name || "-"}/${
          item?.address?.city?.name || "-"
        }/${item?.address?.address || "-"}`,
        item?.steward ? "می باشد" : "نمی باشد",
        item?.limitationAllocation ? "دارد" : "ندارد",
        item?.allocationLimit ? item?.allocationLimit : "-",
        item?.getPosStatus?.hasActivePons ? "دارد" : "ندارد",
        item?.getPosStatus?.lenActiveSessions || "-",
      ];

      if (getRoleFromUrl() !== "KillHouse") {
        commonData.push(
          <Button
            key={`stewards-${i}`}
            onClick={() => {
              const tableData = item?.stewards?.map((option, index) => [
                index + 1,
                option?.guildsName || "-",
                option?.user?.mobile || "-",
              ]);
              dispatch(
                OPEN_MODAL({
                  title: "مباشرین",
                  content: (
                    <SimpleTable
                      paginated
                      title={"مباشرین"}
                      columns={["ردیف", "نام و نام خانوادگی", "تلفن"]}
                      data={tableData}
                    />
                  ),
                })
              );
            }}
          >
            نمایش ({item?.stewards?.length || 0})
          </Button>
        );

        commonData.push(
          <Button
            key={`killHouse-${i}`}
            onClick={() => {
              const tableData = item?.killHouse?.map((option, index) => [
                index + 1,
                option?.name || "-",
                option?.killHouseOperator?.user?.mobile || "-",
              ]);
              dispatch(
                OPEN_MODAL({
                  title: "کشتارگاه ها",
                  content: (
                    <SimpleTable
                      paginated
                      title={"کشتارگاه ها"}
                      columns={["ردیف", "نام و نام خانوادگی", "تلفن"]}
                      data={tableData}
                    />
                  ),
                })
              );
            }}
          >
            نمایش ({item?.killHouse?.length || 0})
          </Button>
        );
      }

      if (
        !["CityJahad", "CityPoultry", "KillHouse"].includes(getRoleFromUrl())
      ) {
        commonData.splice(
          14,
          0,
          item?.productInfo?.totalCarcassesWeight
            ? item.productInfo.totalCarcassesWeight.toLocaleString()
            : "-"
        );
        commonData.splice(10, 0, item?.hasInquiry ? "استعلامی" : "دستی");
        commonData.splice(
          11,
          0,
          item?.activeRegisterCode ? "انجام شده" : "انجام نشده"
        );
      }

      commonData?.push(item?.active ? "فعال" : "غیر فعال");

      commonData.push(
        !item?.isRegistered &&
          item?.registerCode &&
          !item?.loggedRegistrationCode
          ? "در انتظار ورود کد احراز"
          : item?.isRegistered && item?.provinceAcceptState === "pending"
          ? "در انتظار تایید استان"
          : item?.isRegistered
          ? "احراز شده"
          : "احراز نشده"
      );
      if (getRoleFromUrl() !== "KillHouse") {
        commonData.push(
          <ManageGuildsOperations
            guild={item}
            updateTable={updateTable}
            isModal={true}
          />
        );
      }

      return commonData;
    });

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    const response = await dispatch(
      provinceGetTotalGuildsService({
        search: "filter",
        value: textValue,
        page: page,
        page_size: perPage,
        steward: false,
        active_state: activeState,
        is_real_person: true,
        role_key: checkPathStartsWith("province")
          ? selectedSubUser?.key || ""
          : "",
      })
    );

    if (response.payload.error) {
      console.error("Error fetching data:", response.payload.error);
      setData([]);
      setTotalRows(0);
    } else {
      setData(response.payload.data?.results || []);
      setTotalRows(response.payload.data?.count || 0);
    }
  };

  return (
    <Grid
      container
      xs={12}
      justifyContent="center"
      alignItems="center"
      gap={2}
      mt={2}
    >
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <form onSubmit={handleSubmit}>
          <Grid container alignItems="center" gap={SPACING.SMALL}>
            {["KillHouse", "GuildRoom"].includes(getRoleFromUrl()) && (
              <Button
                variant="contained"
                onClick={() => {
                  dispatch(
                    OPEN_MODAL({
                      right: !(window.innerWidth <= 600),
                      bottom: window.innerWidth <= 600,
                      size: window.innerWidth <= 600 ? "small" : "auto",
                      title: "ثبت واحد جدید",
                      content: <CreateGuilds updateTable={updateTable} />,
                    })
                  );
                }}
              >
                ثبت واحد جدید
              </Button>
            )}

            <TextField
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 200 }}
              onChange={handleTextChange}
            />

            {/* <FormControlLabel
              style={{ marginRight: 4 }}
              control={
                <Checkbox
                  checked={isSteward}
                  onChange={handleCheckboxChange}
                  name="checkboxName"
                  color="primary"
                />
              }
              label="نمایش مباشرین"
            /> */}
            {getRoleFromUrl() !== "KillHouse" && (
              <TextField
                select
                size="small"
                label="وضعیت"
                value={activeState}
                onChange={(e) => setActiveState(e.target.value)}
                sx={{ width: 150 }}
              >
                <MenuItem value="all">همه</MenuItem>
                <MenuItem value="active">فعال</MenuItem>
                <MenuItem value="deactive">غیرفعال</MenuItem>
              </TextField>
            )}

            <Button
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </Grid>
        </form>
        {getRoleFromUrl() !== "KillHouse" && (
          <Grid>
            <Tooltip title="خروجی اکسل">
              <a
                href={`${
                  axios.defaults.baseURL
                }guilds_excel/?key=${userKey}&search=filter&value=${textValue}&role=${getRoleFromUrl()}${
                  checkPathStartsWith("province")
                    ? `&role_key=${selectedSubUser?.key}`
                    : ""
                }&active_state=${activeState}`}
                rel="noreferrer"
              >
                <Button color="success">
                  <RiFileExcel2Fill size={32} />
                </Button>
              </a>
            </Tooltip>
          </Grid>
        )}
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={
          getRoleFromUrl() === "CityJahad" || getRoleFromUrl() === "CityPoultry"
            ? [
                "ردیف",
                "شناسه صنف",
                "نام واحد صنفی",
                "نام شخص/شرکت",
                "کدملی",
                "نوع فعالیت",
                "حوزه فعالیت",
                "کدپستی",
                "استان/شهر/آدرس",
                "مباشر",
                "محدودیت تخصیص",
                "حداکثر تخصیص",
                "وضعیت کارتخوان",
                "تعداد کارتخوان ",
                "مباشرین",
                "وضعیت فعالیت",
                "وضعیت",
                "کشتارگاه ها",
              ]
            : getRoleFromUrl() === "KillHouse"
            ? [
                "ردیف",
                "شناسه صنف",
                "نام واحد صنفی",
                "نام شخص/شرکت",
                "کدملی",
                "نوع فعالیت",
                "حوزه فعالیت",
                "کدپستی",
                "استان/شهر/آدرس",
                "مباشر",
                "محدودیت تخصیص",
                "حداکثر تخصیص",
                "وضعیت کارتخوان",
                "تعداد کارتخوان ",
                "وضعیت فعالیت",
                "وضعیت",
                // "عملیات",
              ]
            : [
                "ردیف",
                "شناسه صنف",
                "نام واحد صنفی",
                "نام شخص/شرکت",
                "کدملی",
                "نوع فعالیت",
                "حوزه فعالیت",
                "کدپستی",
                "استان/شهر/آدرس",
                "مباشر",
                "نوع ثبت",
                "احراز شماره موبایل",
                "محدودیت تخصیص",
                "حداکثر تخصیص",
                "وضعیت کارتخوان",
                "تعداد کارتخوان ",
                "وزن خرید (کیلوگرم)",
                "مباشرین",
                "کشتارگاه ها",
                "وضعیت فعالیت",
                "وضعیت",
                "عملیات",
              ]
        }
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="مدیریت اصناف"
      />
    </Grid>
  );
};
