import React, { useEffect, useState } from "react";
import { Button, TextField, Typography } from "@mui/material";
import { useDispatch } from "react-redux";
import { RiSearchLine } from "react-icons/ri";
import {
  CLOSE_MODAL,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { ManageGuildsRequestsOperations } from "../manage-guilds-requests-operations/ManageGuildsRequestsOperations";
import { CreateGuilds } from "../create-guilds/CreateGuilds";
import { provinceGetTotalGuildsService } from "../../services/province-get-total-guilds";
import { provinceGetTotalStewardsService } from "../../services/province-get-total-stewards";
import { formatTime } from "../../../../utils/formatTime";
import { ProvinceLegalGuildsForm } from "../province-legal-guilds-in-province/ProvinceLegalGuildsForm";

export const ManageGuildsRequests = ({ userType }) => {
  const IS_STEWARD = userType === "steward";
  const TABLE_TITLE = `درخواست‌های ثبت ${IS_STEWARD ? "مباشر" : "صنف"}`;
  const dispatch = useDispatch();

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

  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) => {
    dispatch(LOADING_START());
    const response = await dispatch(
      IS_STEWARD
        ? provinceGetTotalStewardsService({
            search: "filter",
            value: textValue,
            page,
            page_size: perPage,
            check: true,
            state: "pending",
          })
        : provinceGetTotalGuildsService({
            search: "filter",
            value: textValue,
            page,
            page_size: perPage,
            check: true,
            state: "pending",
          })
    );
    dispatch(LOADING_END());
    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(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        formatTime(item?.createDate) || "-",
        `${item?.registerarFullname || ""} ${
          item?.registerarMobile ? "(" + item?.registerarMobile + " )" : " "
        }`,
        item?.licenseNumber || "-",
        (IS_STEWARD ? item?.name : 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?.hasInquiry ? "استعلامی" : "دستی",
        item?.activeRegisterCode ? "انجام شده" : "انجام نشده",
        <ManageGuildsRequestsOperations
          updateTable={updateTable}
          key={item?.guildsName}
          item={item}
          userType={userType}
        />,
      ];
    });

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

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());
    setPage(1);
    try {
      const response = await dispatch(
        IS_STEWARD
          ? provinceGetTotalStewardsService({
              search: "filter",
              value: textValue,
              page: 1,
              page_size: perPage,
              check: true,
              state: "pending",
            })
          : provinceGetTotalGuildsService({
              search: "filter",
              value: textValue,
              page: 1,
              page_size: perPage,
              check: true,
              state: "pending",
            })
      );
      setData(response.payload?.data?.results || []);
      setTotalRows(response.payload?.data?.count || 0);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
      dispatch(LOADING_END());
    }
  };
  {
    /*  */
  }
  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        {["AdminX", "SuperAdmin"].includes(getRoleFromUrl()) && (
          <Button
            variant="contained"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: `ثبت ${IS_STEWARD ? "مباشر" : "صنف"} جدید`,
                  size: window.innerWidth <= 600 ? "small" : "auto",
                  content: (
                    <Grid container>
                      <Grid xs={12} mb={2}>
                        <Typography>{`نوع ${
                          IS_STEWARD ? "مباشر" : "صنف"
                        }:`}</Typography>
                      </Grid>
                      <Grid container justifyContent="flex-end" gap={1} xs={12}>
                        <Button
                          variant="contained"
                          color="primary"
                          onClick={() => {
                            dispatch(CLOSE_MODAL());
                            dispatch(
                              OPEN_MODAL({
                                title: `ثبت ${
                                  IS_STEWARD ? "مباشر" : "صنف"
                                } حقیقی جدید`,
                                size:
                                  window.innerWidth <= 600 ? "small" : "auto",
                                content: (
                                  <CreateGuilds updateTable={updateTable} />
                                ),
                              })
                            );
                          }}
                          style={{ flex: 1 }}
                        >
                          حقیقی
                        </Button>
                        <Button
                          style={{ flex: 1 }}
                          variant="outlined"
                          color="primary"
                          onClick={() => {
                            dispatch(CLOSE_MODAL());
                            dispatch(
                              OPEN_MODAL({
                                title: `ثبت ${
                                  IS_STEWARD
                                    ? "مباشر حقوقی جدید"
                                    : "صنف حقوقی جدید"
                                }`,
                                content: (
                                  <ProvinceLegalGuildsForm
                                    onClose={() => dispatch(CLOSE_MODAL())}
                                    updateTable={updateTable}
                                    userType={userType}
                                  />
                                ),
                                size: 400,
                              })
                            );
                          }}
                        >
                          حقوقی
                        </Button>
                      </Grid>
                    </Grid>
                  ),
                })
              );
            }}
          >
            {`ثبت ${IS_STEWARD ? "مباشر" : "صنف"}`}
          </Button>
        )}

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

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