import React, { useEffect, useState } from "react";
import { Button, TextField } from "@mui/material";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch } from "react-redux";
import { RiSearchLine } from "react-icons/ri";
import { fetchOutProvinceLegalBuyers } from "../../services/province-out-province-buyers";
import { ProvinceTrueGuildsOutProvinceOperations } from "../province-true-guilds-out-province/ProvinceTrueGuildsOutProvinceOperations";
import { StewardAddBuyer } from "../../../steward/components/steward-add-buyer/StewardAddBuyer";

export const ProvinceLegalGuildsOutProvince = ({ userType }) => {
  const IS_STEWARD = userType === "steward";
  const TABLE_TITLE = `${IS_STEWARD ? "مباشرین" : "اصناف"} حقوقی خارج استان`;
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  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 fetchApiData = async (page) => {
    dispatch(LOADING_START());
    try {
      const response = await fetchOutProvinceLegalBuyers({
        role: getRoleFromUrl(),
        page: page,
        pageSize: perPage,
        searchValue: textValue,
        buyer_type: IS_STEWARD ? "Steward" : "Guilds",
      });
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      dispatch(LOADING_END());
    }
  };

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

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

  useEffect(() => {
    const d = data?.map((item, i) => {
      const killHouseName = item?.KillHouse?.name || "-";
      const killHouseOperator =
        item?.KillHouse?.killHouseOperator?.user?.fullname || "";
      const killHouseInfo = killHouseOperator
        ? `${killHouseName} (${killHouseOperator})`
        : killHouseName;

      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.unitName || "-",
        (IS_STEWARD
          ? item?.buyer?.nationalId
          : item?.buyer?.parentLegalPersonNationalCode) || "-",
        killHouseInfo,
        item?.province || "-",
        item?.city || "-",
        item?.requestsInfo?.numberOfRequests?.toLocaleString() || "0",
        item?.requestsInfo?.totalQuantity?.toLocaleString() || "0",
        item?.requestsInfo?.totalWeight?.toLocaleString() || "0",
        <ProvinceTrueGuildsOutProvinceOperations
          key={item?.unitName}
          item={item}
          updateTable={() => fetchApiData(1)}
          userType={userType}
        />,
      ];
    });

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

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    fetchApiData(1);
    setPage(1);
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <Button
          variant="contained"
          onClick={() => {
            dispatch(
              DRAWER({
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                size: 340,
                content: (
                  <StewardAddBuyer
                    updateTable={() => {
                      setPage(1);
                      fetchApiData(1);
                    }}
                    buyerType={IS_STEWARD ? "Steward" : "Guilds"}
                  />
                ),
                title: `افزودن ${IS_STEWARD ? "مباشر" : "صنف"} خارج از استان`,
              })
            );
          }}
        >
          {`افزودن ${IS_STEWARD ? "مباشر" : "صنف"}`}
        </Button>
        <Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              value={textValue}
              onChange={handleTextChange}
            />
            <Button
              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={TABLE_TITLE}
      />
    </Grid>
  );
};
