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,
  OPEN_MODAL,
} 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 { fetchOutProvinceRealBuyers } from "../../services/province-out-province-buyers";
import { ProvinceTrueGuildsOutProvinceOperations } from "./ProvinceTrueGuildsOutProvinceOperations";
import { SPACING } from "../../../../data/spacing";
import { StewardAddBuyer } from "../../../steward/components/steward-add-buyer/StewardAddBuyer";

export const ProvinceTrueGuildsOutProvince = ({ 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 fetchOutProvinceRealBuyers({
        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);
  };

  const killHouseList = (item) =>
    item?.kill_house_info ?? item?.killHouseInfo ?? [];
  const stewardList = (item) => item?.steward_info ?? item?.stewardInfo ?? [];

  const openKillHousesModal = (list) => {
    const rows =
      list?.map((entry, idx) => {
        const kh = entry?.Kill_house ?? entry?.KillHouse ?? {};
        const req = entry?.requests_info ?? entry?.requestsInfo ?? {};
        return [
          idx + 1,
          kh?.name ?? "-",
          entry?.fullname ?? "-",
          entry?.mobile ?? "-",
          entry?.unit_name ?? entry?.unitName ?? "-",
          entry?.province ?? "-",
          entry?.city ?? "-",
          (
            req?.number_of_requests ??
            req?.numberOfRequests ??
            0
          ).toLocaleString(),
          (req?.total_quantity ?? req?.totalQuantity ?? 0).toLocaleString(),
          (req?.total_weight ?? req?.totalWeight ?? 0).toLocaleString(),
        ];
      }) ?? [];
    dispatch(
      OPEN_MODAL({
        title: "لیست کشتارگاه ها",
        size: "auto",
        content: (
          <ResponsiveTable
            noPagination
            data={rows}
            columns={[
              "ردیف",
              "نام کشتارگاه",
              "نام و نام خانوادگی",
              "موبایل",
              "نام واحد",
              "استان",
              "شهر",
              "تعداد درخواست",
              "حجم (قطعه)",
              "وزن (کیلوگرم)",
            ]}
            customWidth={"80vw"}
          />
        ),
      })
    );
  };

  const openStewardsModal = (list) => {
    const rows =
      list?.map((entry, idx) => {
        const req = entry?.requests_info ?? entry?.requestsInfo ?? {};
        return [
          idx + 1,
          entry?.fullname ?? "-",
          entry?.mobile ?? "-",
          entry?.unit_name ?? entry?.unitName ?? "-",
          entry?.province ?? "-",
          entry?.city ?? "-",
          (
            req?.number_of_requests ??
            req?.numberOfRequests ??
            0
          ).toLocaleString(),
          (req?.total_quantity ?? req?.totalQuantity ?? 0).toLocaleString(),
          (req?.total_weight ?? req?.totalWeight ?? 0).toLocaleString(),
        ];
      }) ?? [];
    dispatch(
      OPEN_MODAL({
        title: "لیست مباشرین",
        size: "auto",
        content: (
          <ResponsiveTable
            noPagination
            data={rows}
            columns={[
              "ردیف",
              "نام و نام خانوادگی",
              "موبایل",
              "نام واحد",
              "استان",
              "شهر",
              "تعداد درخواست",
              "حجم (قطعه)",
              "وزن (کیلوگرم)",
            ]}
            customWidth={"80vw"}
          />
        ),
      })
    );
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      const khList = killHouseList(item);
      const stList = stewardList(item);
      // const firstKillHouse = khList?.[0];
      // const kh = firstKillHouse?.Kill_house ?? firstKillHouse?.KillHouse ?? {};
      // const killHouseName = kh?.name ?? item?.KillHouse?.name ?? "-";
      // const killHouseOperator =
      //   firstKillHouse?.fullname ??
      //   item?.KillHouse?.killHouseOperator?.user?.fullname ??
      //   "";
      // const killHouseDisplay =
      //   killHouseOperator && killHouseOperator !== "-"
      //     ? `${killHouseName} (${killHouseOperator})`
      //     : killHouseName;

      const totalRequests = khList.reduce(
        (acc, entry) => {
          const r = entry?.requests_info ?? entry?.requestsInfo ?? {};
          return {
            numberOfRequests:
              acc.numberOfRequests +
              (r?.number_of_requests ?? r?.numberOfRequests ?? 0),
            totalQuantity:
              acc.totalQuantity + (r?.total_quantity ?? r?.totalQuantity ?? 0),
            totalWeight:
              acc.totalWeight + (r?.total_weight ?? r?.totalWeight ?? 0),
          };
        },
        { numberOfRequests: 0, totalQuantity: 0, totalWeight: 0 }
      );

      const requestsNum =
        khList.length > 0
          ? totalRequests.numberOfRequests
          : item?.requestsInfo?.numberOfRequests ??
            item?.requests_info?.number_of_requests ??
            0;
      const requestsQty =
        khList.length > 0
          ? totalRequests.totalQuantity
          : item?.requestsInfo?.totalQuantity ??
            item?.requests_info?.total_quantity ??
            0;
      const requestsWt =
        khList.length > 0
          ? totalRequests.totalWeight
          : item?.requestsInfo?.totalWeight ??
            item?.requests_info?.total_weight ??
            0;

      const hasKillHouses = khList?.length > 0;
      const hasStewards = stList?.length > 0;
      const listButtons =
        hasKillHouses || hasStewards ? (
          <Grid container gap={0.5} wrap="nowrap" key={i}>
            {hasKillHouses && (
              <Button
                size="small"
                sx={{
                  minWidth: "fit-content",
                  whiteSpace: "nowrap",
                  fontSize: "0.8125rem",
                }}
                variant="outlined"
                onClick={() => openKillHousesModal(khList)}
              >
                کشتارگاه ها ({khList.length})
              </Button>
            )}
            {hasStewards && (
              <Button
                size="small"
                sx={{
                  whiteSpace: "nowrap",
                  fontSize: "0.8125rem",
                  color: "#008f6b",
                  borderColor: "#008f6b",
                  "&:hover": {
                    borderColor: "#006b52",
                    backgroundColor: "rgba(0, 143, 107, 0.08)",
                  },
                }}
                variant="outlined"
                onClick={() => openStewardsModal(stList)}
              >
                مباشرین ({stList.length})
              </Button>
            )}
          </Grid>
        ) : (
          "-"
        );

      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        `${item?.fullname ?? ""} (${item?.mobile ?? ""})`,
        item?.nationalId ?? "-",
        item?.unit_name ?? item?.unitName ?? "-",
        // killHouseDisplay,
        item?.province ?? "-",
        item?.city ?? "-",
        listButtons,
        (requestsNum ?? 0).toLocaleString(),
        (requestsQty ?? 0).toLocaleString(),
        (requestsWt ?? 0).toLocaleString(),
        <ProvinceTrueGuildsOutProvinceOperations
          key={item?.key ?? item?.unit_name ?? item?.unitName ?? i}
          userType={userType}
          item={item}
          updateTable={() => fetchApiData(page)}
        />,
      ];
    });

    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}
      >
        <Grid>
          <form onSubmit={handleSubmit}>
            <Button
              variant="contained"
              sx={{
                mr: SPACING.SMALL,
              }}
              onClick={() => {
                dispatch(
                  DRAWER({
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    size: 340,
                    content: (
                      <StewardAddBuyer
                        updateTable={() => {
                          setPage(1);
                          fetchApiData(1);
                        }}
                        isRealPerson
                        buyerType={IS_STEWARD ? "Steward" : "Guilds"}
                      />
                    ),
                    title: `افزودن ${
                      IS_STEWARD ? "مباشر" : "صنف"
                    } خارج از استان`,
                  })
                );
              }}
            >
              {`افزودن ${IS_STEWARD ? "مباشر" : "صنف"}`}
            </Button>
            <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>
  );
};
