import {
  Button,
  Pagination,
  TextField,
  Tooltip,
  Typography,
} 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 { RiSearchLine } from "react-icons/ri";

import { ManageGuildsOperations } from "../../province/components/manage-guilds-operations/ManageGuildsOperations";
import { Grid } from "../../../components/grid/Grid";
import { SPACING } from "../../../data/spacing";
import { CreateGuilds } from "../../province/components/create-guilds/CreateGuilds";
import { PageTable } from "../../../components/page-table/PageTable";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../utils/getRoleFromUrl";
import BoxList from "../../../components/box-list/BoxList";
import { provinceGetTotalGuildsService } from "../../province/services/province-get-total-guilds";

const GuildMaangeGuilds = () => {
  const dispatch = useDispatch();
  const [dataTableM, setDataTableM] = useState([]);
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);

  const [textValue, setTextValue] = useState("");

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const fetchApiData = async (page, textValue) => {
    setLoading(true);
    const response = await dispatch(
      provinceGetTotalGuildsService({
        steward: true,
        search: "filter",
        value: textValue,
        page,
        page_size: perPage,
      })
    );

    setData(response.data.results);
    setTotalRows(response.data.count);
    setLoading(false);
  };

  const handlePageChange = (page) => {
    fetchApiData(page, textValue);
  };

  const handlePerRowsChange = async (newPerPage, page) => {
    setLoading(true);
    const response = await dispatch(
      provinceGetTotalGuildsService({
        steward: true,
        search: "filter",
        value: textValue,
        page,
        page_size: perPage,
      })
    );

    setData(response.data.results);
    setTotalRows(response.data.count);
    setPerPage(newPerPage);

    setLoading(false);
    dispatch(LOADING_END());
  };

  const [page, setPage] = useState(0);
  const handleChangePageM = (event, newPage) => {
    dispatch(LOADING_START());
    setPage(newPage);
    fetchApiData(newPage + 1, textValue);
  };

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

  const updateTable = () => {
    fetchApiData(1);
  };

  const columns = [
    {
      name: "شناسه صنف",
      selector: (item) => item.guildsId,
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "نام واحد صنفی",
      selector: (item) => item?.guildsName,
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "نام شخص/شرکت",
      selector: (item) => `${item?.user?.fullname} (${item?.user?.mobile})`,
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "100px",
    },
    {
      name: "کدملی",
      selector: (item) => item?.user?.nationalId,
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "100px",
    },
    {
      name: "نوع فعالیت",
      selector: (item) => item?.typeActivity,
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "حوزه فعالیت",
      selector: (item) => item?.areaActivity,
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "کدپستی",
      selector: (item) => item?.address?.postalCode,
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "استان/شهر/آدرس",
      selector: (item) =>
        `${item?.address?.province.name}/${item?.address?.city.name}/${item?.address?.address}`,
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "مباشر",
      selector: (item) => (item?.steward ? "می باشد" : "نمی باشد"),
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "محدودیت تخصیص",
      selector: (item) => (item?.limitationAllocation ? "دارد" : "ندارد"),
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "حداکثر تخصیص",
      selector: (item) => item?.allocationLimit,
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "مباشر",
      selector: (item) =>
        item?.centersAllocation?.map((item) => item.label).join(" - "),
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "کشتارگاه",
      selector: (item) => {
        return item?.killHouseInfo
          ?.map((item) => `${item.name} (${item.mobile})`)
          .join(" - ");
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "وضعیت",
      selector: (item) => {
        let state = "";
        if (item?.provinceAcceptState === "accepted") {
          state = "تایید شده";
        } else if (item?.provinceAcceptState === "rejected") {
          state = "رد شده";
        } else if (item?.provinceAcceptState === "pending") {
          state = "در انتظار تایید";
        }
        return state;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "عملیات",
      selector: (item, i) => (
        <ManageGuildsOperations
          key={i + item?.guildsId}
          item={item}
          updateTable={updateTable}
        />
      ),
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "110px",
    },
  ];

  const handleSubmit = async (event) => {
    event.preventDefault();
    setLoading(true);
    try {
      const response = await dispatch(
        provinceGetTotalGuildsService({
          steward: true,
          search: "filter",
          value: textValue,
        })
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  };

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

  const getItemState = (item) => {
    let state = "";
    if (item?.provinceAcceptState === "accepted") {
      state = "تایید شده";
    } else if (item?.provinceAcceptState === "rejected") {
      state = "رد شده";
    } else if (item?.provinceAcceptState === "pending") {
      state = "در انتظار تایید";
    }
    return state;
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        item.guildsId,
        item?.guildsName,
        `${item?.user?.fullname} (${item?.user?.mobile})`,
        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?.centersAllocation?.map((item) => item.label).join(" - "),
        item?.killHouseInfo
          ?.map((item) => `${item.name} (${item.mobile})`)
          .join(" - "),
        getItemState(item),
        <ManageGuildsOperations key={i + item?.guildsId} item={item} />,
      ];
    });

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

  const columnNames = columns.map((column) => column.name);
  const isMobile = window.innerWidth <= 600;

  const tableTitle = (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      gap={2}
      paddingTop={2}
      mb={1}
      width="100%"
    >
      <Grid
        container
        width="100%"
        alignItems="center"
        justifyContent="space-between"
        gap={SPACING.SMALL}
      >
        <form onSubmit={handleSubmit}>
          <Grid container alignItems="center" gap={SPACING.SMALL}>
            <Typography>مدیریت اصناف</Typography>
            <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>
          {getRoleFromUrl() !== "CityJahad" && (
            <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>
          )}

          <Tooltip title="خروجی اکسل">
            <a
              href={`${
                axios.defaults.baseURL
              }guilds_excel/?key=${userKey}&role=${getRoleFromUrl()}&search=filter&value=${textValue}`}
              rel="noreferrer"
            >
              <Button color="success">
                <RiFileExcel2Fill size={32} />
              </Button>
            </a>
          </Tooltip>
        </Grid>
      </Grid>
    </Grid>
  );

  return (
    <Grid>
      {isMobile ? (
        <Grid container justifyContent="center" gap={SPACING.SMALL}>
          {tableTitle}
          <BoxList columns={columnNames} data={dataTableM} />
          <Pagination
            count={Math.ceil(totalRows / 10)}
            page={page + 1}
            variant="outlined"
            onChange={(event, newPage) => {
              handleChangePageM(event, newPage - 1);
            }}
          />
        </Grid>
      ) : (
        <PageTable
          title={tableTitle}
          columns={columns}
          data={data}
          progressPending={loading}
          pagination
          paginationServer
          paginationTotalRows={totalRows}
          onChangeRowsPerPage={handlePerRowsChange}
          onChangePage={handlePageChange}
        />
      )}
    </Grid>
  );
};

export default GuildMaangeGuilds;
