import { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { Button, Tooltip } from "@mui/material";
import axios from "axios";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { RiFileExcel2Fill } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import { useSelector } from "react-redux";
import { ProvinceReturnPurchasesOperations } from "./ProvinceReturnPurchasesOperations";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const ReturnedAllocated = ({
  data,
  page,
  perPage,
  totalRows,
  handlePageChange,
  handlePerRowsChange,
  textValue,
  updateTable,
}) => {
  const [dataTable, setDataTable] = useState();
  const [, , selectedDate1, , selectedDate2] = useContext(AppContext);
  const userKey = useSelector((state) => state.userSlice.userProfile.key);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  useEffect(() => {
    const d = data?.map((item, i) => {
      let state = "";
      if (item.state === "pending") {
        state = "در انتظار تایید";
      } else if (item.state === "accepted") {
        state = "تایید شده";
      } else if (item.state === "rejected") {
        state = "رد شده";
      }

      let requestType = "";
      if (item?.market) {
        requestType = "پنل معاملات";
      } else if (item?.directBuying) {
        requestType = "خرید مستقیم";
      } else if (item?.warehouse) {
        requestType = "انبار";
      } else {
        requestType = "اتحادیه";
      }

      const rows = [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.orderCode || "-",
        requestType,
        item?.poultryUnitName,
        `${item?.poultryFullname} (${item?.poultryMobile})`,
        item?.poultryCity,
        formatJustDate(item?.killingDate),
        item?.poultryRequestQuantity?.toLocaleString(),
        formatTime(item?.createDate),
        item?.killhouseUser.name || "-",
        item?.killhouseUser.city || "-",
        item?.poultryAmount?.toLocaleString() + " ﷼",
        item?.killHousePrice?.toLocaleString() + " ﷼",
        item?.quantity?.toLocaleString(),
        state,
        item?.firstCarAllocatedQuantity > 0 ? "دارد" : "ندارد",
        (item?.quantity - item?.totalKilledQuantity)?.toLocaleString(),
        (item?.returner
          ? `${item?.returner.fullname} (${item?.returner?.mobile})`
          : "سیستم") +
          " " +
          formatTime(item?.modifyDate),
      ];

      if (["AdminX", "SuperAdmin"].includes(getRoleFromUrl())) {
        if (item?.returnTrash === true) {
          rows.push(
            <ProvinceReturnPurchasesOperations
              item={item}
              updateTable={updateTable}
              key={`operation-${item?.key}`}
            />
          );
        } else {
          rows.push("-");
        }
      }

      return rows;
    });

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

  const columns = [
    "ردیف",
    "کدسفارش",
    "نوع درخواست",
    "نام فارم",
    "نام مرغدار",
    "شهر مرغدار",
    "تاریخ کشتار",
    "تعداد درخواست",
    "تاریخ ثبت تخصیص",
    "نام کشتارگاه",
    "شهر کشتارگاه",
    "قیمت مرغدار",
    "قیمت کشتارگاه",
    "تعداد تخصیص",
    "وضعیت تایید",
    "وضعیت تخصیص ماشین",
    "مانده قابل تخصیص",
    "برگشت دهنده",
  ];

  if (["AdminX", "SuperAdmin"].includes(getRoleFromUrl())) {
    columns.push("عملیات");
  }

  return (
    <Grid
      container
      justifyContent="end"
      alignItems="center"
      mb={SPACING.MEDIUM}
      mt={SPACING.SMALL}
    >
      <Grid>
        <Tooltip title="خروجی اکسل">
          <a
            href={`${
              axios.defaults.baseURL
            }return_province_request_excel/?role=${getRoleFromUrl()}${
              checkPathStartsWith("province")
                ? `&role_key=${selectedSubUser?.key}`
                : ""
            }&date1=${selectedDate1}&date2=${selectedDate2}&search=filter&value=${textValue}&key=${userKey}`}
            rel="noreferrer"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>
      </Grid>

      <ResponsiveTable
        title="تخصیص‌های بازگشتی"
        columns={columns}
        data={dataTable}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
      />
    </Grid>
  );
};
