import React, { useEffect, useState } from "react";
import { Button, TextField, Tooltip } from "@mui/material";
import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { SPACING } from "../../../../data/spacing";
import { CreateGuilds } from "../../../province/components/create-guilds/CreateGuilds";
import { PspManageGuildsOperation } from "../psp-manage-guilds-operation/PspManageGuildsOperation";
// import { PspPosList } from "../psp-pos-list/PspPosList";
// import { PspCreatePos } from "../psp-create-pos/PspCreatePos";
// import { PspSubmitGuildCondition } from "../psp-submit-guild-condition/PspSubmitGuildCondition";
// import { PspSessions } from "../psp-sessions/PspSessions";

export const PspManageGuilds = () => {
  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 dispatch = useDispatch();

  const userInfo = useSelector((state) => state.userSlice);

  const fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `total_guilds_for_companies/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}`
    );

    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

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

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

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

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item.guildsId,
        item?.guildsName,
        `${item?.user?.fullname} (${item?.user?.mobile})`,
        item?.user?.nationalId,
        item?.typeActivity,
        item?.areaActivity,
        `${item?.user?.province}/${item?.user?.city}/${
          item?.user?.address ? item?.user?.address : ""
        }`,
        item?.steward ? "می باشد" : "نمی باشد",
        item?.provinceAcceptState === "accepted"
          ? "تایید شده"
          : item?.provinceAcceptState === "rejected"
          ? "رد شده"
          : "در انتظار تایید",

        `${item?.condition || "توضیحاتی وجود ندارد"} (${
          item?.descriptionCondition
        })`,

        // <Button
        //   key={i}
        //   disabled={!item?.guildPos}
        //   size="small"
        //   className="first-step"
        //   variant={"contained"}
        //   onClick={() => {
        //     dispatch(
        //       DRAWER({
        //         title: "نشست های فعال",
        //         right: !(window.innerWidth <= 600),
        //         bottom: window.innerWidth <= 600,
        //         content: (
        //           <PspSessions item={item} updateTable={updateTable} key={i} />
        //         ),
        //       })
        //     );
        //   }}
        // >
        //   مشاهده
        // </Button>,
        <PspManageGuildsOperation
          selectedAge1={null}
          selectedAge2={null}
          updateTable={updateTable}
          item={item}
          key={"4"}
          // readOnly={isReadOnly}
        />,
        // <Grid container gap={1} p={1} justifyContent="center" key={i}>
        //   <Grid container gap={1} key={i}>
        //     {/* {item?.numberOfPos ? (
        //       <Button
        //         key={i}
        //         disabled={item?.provinceAcceptState !== "accepted"}
        //         size="small"
        //         className="first-step"
        //         variant={"contained"}
        //         onClick={() => {
        //           dispatch(
        //             DRAWER({
        //               title: "لیست دستگاه های pos",
        //               right: !(window.innerWidth <= 600),
        //               bottom: window.innerWidth <= 600,
        //               content: (
        //                 <PspPosList
        //                   key={i}
        //                   item={item}
        //                   updateTable={updateTable}
        //                 />
        //               ),
        //             })
        //           );
        //         }}
        //       >
        //         مشاهده
        //       </Button>
        //     ) : (
        //       ""
        //     )} */}

        //     <Tooltip title="ثبت دستگاه POS" placement="top">
        //       <Button
        //         disabled={item?.provinceAcceptState !== "accepted"}
        //         size="small"
        //         className="first-step"
        //         variant={"outlined"}
        //         onClick={() => {
        //           dispatch(
        //             DRAWER({
        //               title: "ایجاد دستگاه",
        //               right: !(window.innerWidth <= 600),
        //               bottom: window.innerWidth <= 600,
        //               content: (
        //                 <PspCreatePos
        //                   key={i}
        //                   item={item}
        //                   updateTable={updateTable}
        //                 />
        //               ),
        //             })
        //           );
        //         }}
        //       >
        //         <RiBankCard2Line size={18} />
        //       </Button>
        //     </Tooltip>
        //   </Grid>
        //   <Tooltip title="جهت مطالعه توضیحات کلیک کنید" placement="top">
        //     <Typography
        //       key={i}
        //       sx={{ cursor: "pointer" }}
        //       color="error"
        //       variant="body2"
        //       onClick={() => {
        //         dispatch(
        //           OPEN_MODAL({
        //             title: "مشاهده توضیحات",
        //             content: (
        //               <Typography key={i}>
        //                 توضیحات: {item.descriptionCondition}
        //               </Typography>
        //             ),
        //           })
        //         );
        //       }}
        //     >
        //       {item.condition}
        //     </Typography>
        //   </Tooltip>

        //   <Tooltip
        //     title={item?.condition ? "ویرایش وضعیت صنف" : "ثبت وضعیت صنف"}
        //     placement="top"
        //   >
        //     <Button
        //       disabled={item?.provinceAcceptState !== "accepted"}
        //       variant="contained"
        //       size="small"
        //       ml={1}
        //       onClick={() => {
        //         dispatch(
        //           OPEN_MODAL({
        //             title: "ثبت  توضیحات",
        //             content: (
        //               <PspSubmitGuildCondition
        //                 key={i}
        //                 item={item}
        //                 updateTable={updateTable}
        //               />
        //             ),
        //           })
        //         );
        //       }}
        //     >
        //       <RiAddLine size={18} />
        //     </Button>
        //   </Tooltip>
        // </Grid>,
      ];
    });

    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_for_companies/?role=${getRoleFromUrl()}&search=filter&value=${textValue}`
      );

      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const tableTitle = (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      gap={2}
      mb={1}
      padding={2}
      width="100%"
    >
      <Grid
        container
        width="100%"
        alignItems="center"
        justifyContent="space-between"
        gap={SPACING.SMALL}
      >
        <form onSubmit={handleSubmit}>
          <Grid container alignItems="center" gap={SPACING.SMALL}>
            <TextField
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
            <Tooltip title="خروجی اکسل">
              <a
                href={`${axios.defaults.baseURL}pos_excel/?&key=${userInfo?.userProfile?.key}`}
                rel="noreferrer"
              >
                <Button color="success">
                  <RiFileExcel2Fill size={32} />
                </Button>
              </a>
            </Tooltip>
          </Grid>
        </form>

        <Grid container alignItems="center" gap={SPACING.SMALL}>
          <Tooltip title="ثبت صنف جدید" placement="top">
            <Button
              variant="contained"
              onClick={() => {
                dispatch(
                  OPEN_MODAL({
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    title: "ثبت واحد جدید",
                    size: window.innerWidth <= 600 ? "small" : "auto",
                    content: <CreateGuilds updateTable={updateTable} />,
                  })
                );
              }}
            >
              ثبت صنف جدید
            </Button>
          </Tooltip>
        </Grid>
      </Grid>
    </Grid>
  );

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      {tableTitle}
      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "شناسه صنف",
          "نام واحد صنفی",
          "نام شخص/شرکت",
          "کدملی",
          "نوع فعالیت",
          "حوزه فعالیت",
          "آدرس",
          "مباشر",
          "وضعیت احراز",
          "توضیحات شرکت psp",
          "عملیات",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="مدیریت اصناف"
      />
    </Grid>
  );
};
