import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Button, TextField } from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { provinceGetTotalGuildsService } from "../../services/province-get-total-guilds";
import { ProvinceLegalGuildsForm } from "./ProvinceLegalGuildsForm";
import { ProvinceLegalGuildsOperations } from "./ProvinceLegalGuildsOperations";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { RiSearchLine } from "react-icons/ri";
import { provinceGetTotalStewardsService } from "../../services/province-get-total-stewards";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";
import { formatTime } from "../../../../utils/formatTime";

export const ProvinceLegalGuildsInProvince = ({ userType }) => {
  const IS_STEWARD = userType === "steward";
  const TABLE_TITLE = `${IS_STEWARD ? "مباشرین" : "اصناف"} حقوقی داخل استان`;
  const dispatch = useDispatch();
  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 selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  const handleTextChange = (e) => setTextValue(e.target.value);

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

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

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

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

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

  useEffect(() => {
    if (!data || !Array.isArray(data)) {
      setTableData([]);
      return;
    }
    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?.provinceName || "-",
        item?.cityName || "-",
        item?.typeActivity || "-",
        item?.active ? "فعال" : "غیر فعال",
        <ProvinceLegalGuildsOperations
          key={`operations-${item?.key || i}`}
          item={item}
          updateTable={updateTableData}
          userType={userType}
        />,
      ];
    });
    setTableData(d);
  }, [data, page, perPage]);

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

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

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

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

  return (
    <Grid item gap={SPACING.SMALL} p={2} xs={12}>
      <Grid
        container
        justifyContent="start"
        alignItems="center"
        gap={SPACING.SMALL}
        mb={SPACING.SMALL}
      >
        <Button
          variant="contained"
          color="primary"
          onClick={() =>
            dispatch(
              OPEN_MODAL({
                title: `ثبت ${IS_STEWARD ? "مباشر جدید" : "صنف جدید"}`,
                content: (
                  <ProvinceLegalGuildsForm
                    onClose={() => dispatch(CLOSE_MODAL())}
                    updateTable={updateTableData}
                    userType={userType}
                  />
                ),
                size: "auto",
              })
            )
          }
        >
          {`ثبت ${IS_STEWARD ? "مباشر" : "واحد صنفی"}`}
        </Button>
        <form onSubmit={handleSubmit}>
          <Grid container alignItems="center" gap={SPACING.SMALL}>
            <TextField
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 200 }}
              value={textValue}
              onChange={handleTextChange}
            />

            <Button
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </Grid>
        </form>
      </Grid>

      <Grid item xs={12}>
        <ResponsiveTable
          title={TABLE_TITLE}
          columns={[
            "ردیف",
            "تاریخ ثبت",
            "ثبت کننده",
            "شناسه حقوقی",
            "نام واحد",
            "نام و نام خانوادگی",
            "شماره همراه",
            "استان",
            "شهر",
            "نوع فعالیت",
            "وضعیت",
            "عملیات",
          ]}
          data={tableData}
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
        />
      </Grid>
    </Grid>
  );
};
