import React, { useContext, useEffect, useState } from "react";
import {
  Button,
  IconButton,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import {
  CLOSE_MODAL,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { formatJustDate } from "../../../../utils/formatTime";
import { RiFileExcel2Fill } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import { RiSearchLine } from "react-icons/ri";
import { SlaughterColdHouseBarsOperations } from "../slaughter-cold-house-bars-operations/SlaughterColdHouseBarsOperations";
import { getKillhouseApprovedPriceState } from "../../../province/services/get-approved-price-state";
import { slaughterInventoryFinalSubmitService } from "../../services/slaughter-inventory-final-submit";
import { SPACING } from "../../../../data/spacing";
import { SlaughterAllocateToColdHouse } from "../slaughter-allocate-to-coldhouse/SlaughterAllocateToColdHouse";
import TuneIcon from "@mui/icons-material/Tune";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";
export const SlaughterColdHouseBars = ({
  selectedDate1,
  selectedDate2,
  title,
  type,
  withDate,
  coldHouseKey,
  getDashboardsData,
  remainWeight,
}) => {
  const dispatch = useDispatch();
  const userKey = useSelector((state) => state.userSlice.userProfile.key);
  const [openNotif] = useContext(AppContext);
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const { priceInfo } = useSelector((state) => state.slaughterSlice);

  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());
    const response = await axios.get(
      `steward-allocation/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${
        checkPathStartsWith("slaughter")
          ? `&role_key=${selectedSubUser?.key}`
          : ""
      }${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }&page=${page}&page_size=${perPage}&cold_house=true&type=${type}&cold_house_key=${coldHouseKey}`
    );
    dispatch(
      getKillhouseApprovedPriceState({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    );

    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

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

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

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

  const getLastItem = (item) => {
    if (item?.systemRegistrationCode) {
      return [
        <IconButton
          key={item}
          disabled={true}
          aria-label="disabled-button"
          color="primary"
        >
          <TuneIcon />
        </IconButton>,
      ];
    } else {
      return [
        <SlaughterColdHouseBarsOperations
          key={item}
          fetchData={updateTable}
          fetchApiData={getDashboardsData}
          item={item}
          priceInfo={priceInfo}
          remainWeight={remainWeight}
        />,
      ];
    }
  };
  const getLastItemTitle = () => {
    if (type === "output") {
      return ["عملیات"];
    } else {
      return [];
    }
  };
  const isOut = title === "بارهای خارج شده";

  useEffect(() => {
    const d = data?.map((item, i) => {
      let registrationCodeStatus;
      switch (item?.receiverState) {
        case "pending":
          registrationCodeStatus = "در انتظار تایید";
          break;
        case "accepted":
          registrationCodeStatus = "تایید شده";
          break;

        case "rejected":
          registrationCodeStatus = "رد شده";
          break;
        default:
          registrationCodeStatus = "-";
      }

      console.log(item);

      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        formatJustDate(item?.date),
        isOut
          ? item?.toGuilds
            ? "سردخانه به صنف"
            : item?.otherColdHouse
            ? "سردخانه به سردخانه"
            : item?.toStewards
            ? "سردخانه به مباشر"
            : "-"
          : `${item?.killHouse ? "کشتارگاه" : "سردخانه"} به سردخانه`,
        isOut
          ? item?.toGuilds
            ? `${item?.toGuilds?.guildsName} ( ${item?.toGuilds?.user?.fullname} ${item?.toGuilds?.user?.mobile})`
            : item?.otherColdHouse
            ? item?.otherColdHouse?.steward
              ? `${item?.otherColdHouse?.steward?.user?.fullname} (${item?.otherColdHouse?.steward?.user?.mobile})`
              : `${item?.otherColdHouse?.killHouse?.name} (${item?.otherColdHouse?.killHouse?.killHouseOperator?.user?.fullname} ${item?.otherColdHouse?.killHouse?.killHouseOperator?.user?.mobile})`
            : `${item?.toStewards?.name} (${item?.toStewards?.user?.fullname}${item?.toStewards?.user?.mobile})`
          : item?.killHouse
          ? `${item.toColdHouse?.name} (${item.toColdHouse?.killHouse?.killHouseOperator?.user?.mobile})`
          : `${item?.otherColdHouse?.name} ${item?.otherColdHouse?.killHouse?.killHouseOperator?.user?.mobile}`,
        item?.sellType === "exclusive" ? "اختصاصی" : "آزاد",
        item?.amount?.toLocaleString() + " ریال",
        item?.totalAmount?.toLocaleString() + " ریال",
        // item?.realNumberOfCarcasses?.toLocaleString(),
        item?.realWeightOfCarcasses?.toLocaleString(),
        item?.loggedRegistrationCode?.toLocaleString(),
        item?.systemRegistrationCode === true
          ? "کد احراز ارسال شده"
          : "در انتظار ارسال کد احراز",

        registrationCodeStatus,
        // item?.receiverRealNumberOfCarcasses?.toLocaleString(),
        // item?.receiverRealWeightOfCarcasses?.toLocaleString(),
        ...getLastItem(item),
      ];
    });

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

  useEffect(() => {
    fetchApiData(1);
  }, [
    dispatch,
    selectedDate1,
    selectedDate2,
    perPage,
    withDate,
    selectedSubUser?.key,
  ]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `steward-allocation/?role=${getRoleFromUrl()}${
          checkPathStartsWith("slaughter")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }&search=filter&value=${textValue}${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
        }&page=${1}&page_size=${perPage}&cold_house=true&type=${type}&cold_house_key=${coldHouseKey}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  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(
              OPEN_MODAL({
                title: "ثبت توزیع/ فروش سرد خانه",
                content: (
                  <SlaughterAllocateToColdHouse
                    updateTable={getDashboardsData}
                    sellerType={"ColdHouse"}
                    sellType="exclusive"
                    fetchApiData={fetchApiData}
                    coldHouseKey={coldHouseKey}
                    remainWeight={remainWeight}
                  />
                ),
              })
            );
          }}
        >
          ثبت توزیع/ فروش
        </Button>

        {type === "output" && (
          <Button
            disabled={!tableData.length}
            variant="outlined"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "ثبت نهایی",
                  content: (
                    <Grid container gap={SPACING.SMALL}>
                      <Typography>
                        در صورت ثبت نهایی انجام هیچگونه عملیاتی مانند حذف و
                        ویرایش امکان پذیر نمی باشد.
                      </Typography>
                      <Grid
                        container
                        direction="column"
                        gap={SPACING.TINY}
                        width="100%"
                      >
                        <Button
                          fullWidth
                          variant="contained"
                          onClick={() => {
                            dispatch(
                              slaughterInventoryFinalSubmitService({
                                steward_allocation_list: data.map(
                                  (item) => item.key
                                ),
                              })
                            ).then((r) => {
                              dispatch(CLOSE_MODAL());
                              if (r.payload.error) {
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: r.payload.error,
                                  severity: "error",
                                });
                              } else {
                                updateTable();
                                fetchApiData(1);
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "عملیات با موفقیت انجام شد.",
                                  severity: "success",
                                });
                              }
                            });
                          }}
                        >
                          تایید
                        </Button>
                        <Button
                          fullWidth
                          color="error"
                          variant="contained"
                          onClick={() => {
                            dispatch(CLOSE_MODAL());
                          }}
                        >
                          لغو
                        </Button>
                      </Grid>
                    </Grid>
                  ),
                })
              );
            }}
          >
            تایید نهایی (یکجا)
          </Button>
        )}

        <Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
        </Grid>
        <Tooltip title="خروجی اکسل">
          {/* <a
                href={`${axios.defaults.baseURL}0/hatching_excel/`}
                rel="noreferrer"
              > */}
          <Button
            color="success"
            onClick={() => {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                severity: "success",
              });
              const link = `${
                axios.defaults.baseURL
              }cold_house_excel/?role=${getRoleFromUrl()}${
                checkPathStartsWith("slaughter")
                  ? `&role_key=${selectedSubUser?.key}`
                  : ""
              }&key=${userKey}&type=${type}${
                withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
              }&cold_house_key=${coldHouseKey}&cold_house=true`;
              window.location.href = link;
            }}
          >
            <RiFileExcel2Fill size={32} />
          </Button>
          {/* </a> */}
        </Tooltip>
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "تاریخ ثبت",
          "نوع تخصیص",
          "مشخصات خریدار",
          "نوع فروش",
          "قیمت هر کیلو",
          "قیمت کل",
          // "حجم تخصیصی",
          "وزن تخصیصی",
          "کد احراز",
          "وضعیت کد احراز",
          "وضعیت",
          // "حجم تایید شده",
          // "وزن تایید شده",
          ...getLastItemTitle(),
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title={title}
      />
    </Grid>
  );
};
