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

export const ReturnedCargo = ({
  data,
  page,
  perPage,
  totalRows,
  handlePageChange,
  handlePerRowsChange,
  textValue,
  updateTable,
}) => {
  const [dataTable, setDataTable] = useState();
  const [, , selectedDate1, , selectedDate2] = useContext(AppContext);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const userKey = useSelector((state) => state.userSlice.userProfile.key);
  useEffect(() => {
    const mappedData = 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?.poultryRequest?.market) {
        requestType = "پنل معاملات";
      } else if (item?.poultryRequest?.directBuying) {
        requestType = "خرید مستقیم";
      } else if (item?.warehouse) {
        requestType = "انبار";
      } else {
        requestType = "اتحادیه";
      }

      let killType = "";
      if (item?.poultryRequest?.freezing) {
        killType = "انجماد";
      } else if (item?.poultryRequest?.export) {
        killType = "صادرات";
      } else {
        killType = "عادی";
      }

      const rows = [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.barCode || "-",
        item?.poultryRequest?.orderCode || "-",
        requestType,
        killType,
        item?.poultryRequest?.poultry?.unitName || "-",
        `${item?.poultryRequest?.poultry?.user?.fullname || "-"} (${
          item?.poultryRequest?.poultry?.user?.mobile || "-"
        })`,
        item?.poultryRequest?.poultry?.address?.city?.name || "-",
        item?.killRequest?.reciveDate
          ? formatTime(item?.killRequest?.reciveDate)
          : "-",
        item?.quantity?.toLocaleString(),
        item?.createDate ? formatTime(item?.createDate) : "-",
        item?.killhouseUser?.name || item?.killer?.name || "-",
        item?.killhouseUser?.killHouseOperator?.user?.city?.name ||
          item?.killer?.killHouseOperator?.user?.city?.name ||
          "-",
        item?.weightInfo?.weight?.toLocaleString() || "-",
        item?.weightInfo?.indexWeight?.toLocaleString() || "-",
        item?.acceptedRealQuantity?.toLocaleString(),
        item?.acceptedRealWeight?.toLocaleString(),
        item?.poultryRequest?.amount?.toLocaleString() + " ﷼" || "-",
        item?.weightInfo?.killHousePrice?.toLocaleString() + " ﷼" || "-",
        state,
        item?.car?.pelak || "-",
        item?.car?.driverName || "-",
        item?.nonReceipt ? "دارد" : "ندارد",
        item?.nonReceiptMessage || "-",
        (item?.nonReceipt && item?.mainNonReceipt ? `کاربر` : "سیستم") +
          " " +
          formatTime(item?.modifyDate),
      ];

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

      return rows;
    });
    setDataTable(mappedData);
  }, [data, page, perPage]);

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

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

  return (
    <Grid container alignItems="center" justifyContent="end">
      <Grid>
        <Tooltip title="خروجی اکسل">
          <a
            href={`${
              axios.defaults.baseURL
            }return_kill_house_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>
  );
};
