import React, { useEffect, useState } from "react";
import { Button, TextField } from "@mui/material";
import { useDispatch } from "react-redux";
import axios from "axios";
import { RiSearchLine } from "react-icons/ri";
import {
  // DRAWER,
  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";

export const ManageGuildsRequests = () => {
  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 axios.get(
      `total_guilds/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}&check=true&state=pending`
    );
    dispatch(LOADING_END());
    setData(response.data?.results || []);
    setTotalRows(response.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,
        // item?.killHouseInfo?.length
        //   ? item?.killHouseInfo
        //       ?.map((item) => {
        //         const type = item?.killer ? "کشتارکن" : "کشتارگاه";
        //         return `${type} ${item?.name} (${item?.mobile})`;
        //       })
        //       .join(" - ")
        //   :
        `${item?.registerarFullname || ""} ${
          item?.registerarMobile ? "(" + item?.registerarMobile + " )" : " "
        }`,
        item?.licenseNumber || "-",
        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?.hasInquiry ? "استعلامی" : "دستی",
        item?.activeRegisterCode ? "انجام شده" : "انجام نشده",
        <ManageGuildsRequestsOperations
          updateTable={updateTable}
          key={item?.guildsName}
          guild={item}
        />,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `total_guilds/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&page=${1}&page_size=${perPage}&check=true&state=pending`
      );
      setData(response.data?.results || []);
      setTotalRows(response.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: "ثبت واحد جدید",
                  size: window.innerWidth <= 600 ? "small" : "auto",
                  content: <CreateGuilds updateTable={updateTable} />,
                })
              );
            }}
          >
            ثبت واحد جدید
          </Button>
        )}

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

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