import { useCallback } from "react";
import { Button, TextField, Tooltip, Typography } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import axios from "axios";
import moment from "moment/moment";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";

import { AppContext } from "../../../../contexts/AppContext";

import { SPACING } from "../../../../data/spacing";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
// import { EnterAuthCodeDirectBuy } from "../enter-auth-code-direct-buy/EnterAuthCodeDirectBuy";
import { SlaughterFreeBuyOperations } from "../slaughter-free-buy-operations/SlaughterFreeBuyOperations";
import { SlaughterSubmitFreeBuy } from "../slaughter-submit-free-buy/SlaughterSubmitFreeBuy";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { paymentGetDeadLines } from "../../services/payment-get-deadlines";
import EditVerificationDirectBuy from "../edit-verification-direct-buy/EditVerificationDirectBuy";
import SlaughterBuyPdfKillRequest from "../../../province/components/province-settlement-pdf-kill-request/ProvinceSettlementPdfKillRequest";
import { slaughterGetFreeBuyDashboardService } from "../../services/slaughter-free-buy-dashboard";
import { slaughterGetFreeBuyRequests } from "../../services/slaughter-get-free-buy-requests";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterFreeBuy = () => {
  const dispatch = useDispatch();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const [poultryCodeMandatory, setPoultryCodeMandatory] = useState(false);
  const [dashboardData, setDashboardData] = useState([]);
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  useEffect(() => {
    dispatch(
      paymentGetDeadLines({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    ).then((response) => {
      setPoultryCodeMandatory(response.payload.data?.poultryCodeMandatory);
    });
  }, [selectedSubUser?.key]);

  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 handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const getDashboardData = () => {
    dispatch(
      slaughterGetFreeBuyDashboardService({
        direct_buying: true,
        date1: selectedDate1,
        date2: selectedDate2,
        role: getRoleFromUrl(),
        search: "filter",
        value: textValue,
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  const fetchApiData = useCallback(
    async (pageNumber = page) => {
      try {
        const response = await dispatch(
          slaughterGetFreeBuyRequests({
            date1: selectedDate1,
            date2: selectedDate2,
            value: textValue || "",
            page: pageNumber,
            page_size: perPage,
            role_key: checkPathStartsWith("slaughter")
              ? selectedSubUser?.key || ""
              : "",
          })
        );
        if (response.payload?.data) {
          getDashboardData();
          setData(response.payload.data.results);
          setTotalRows(response.payload.data.count);
        }
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    },
    [
      selectedDate1,
      selectedDate2,
      perPage,
      page,
      textValue,
      dispatch,
      selectedSubUser?.key,
    ]
  );

  const updateTable = useCallback(() => {
    fetchApiData(1);
  }, [fetchApiData]);

  useEffect(() => {
    fetchApiData(1);
  }, [fetchApiData]);
  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };

  const handlePageChange = (page) => {
    fetchApiData(page, textValue);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    try {
      const response = await dispatch(
        slaughterGetFreeBuyRequests({
          date1: selectedDate1,
          date2: selectedDate2,
          value: textValue || "",
          role_key: checkPathStartsWith("slaughter")
            ? selectedSubUser?.key || ""
            : "",
        })
      );
      if (response.payload?.data) {
        setData(response.payload.data.results);
        setTotalRows(response.payload.data.count);
      }
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const getItemState = (item) => {
    let state = "";
    if (item.finalAccept === false) {
      state = "در انتظار ارسال به استان";
    } else if (poultryCodeMandatory && !item?.inputDirectBuyingCode) {
      state = "در انتظار ورود کد احراز";
    } else if (item?.directBuyingState === "rejected") {
      state = "رد شده";
    } else if (item?.directBuyingState === "accepted") {
      state = "تایید شده";
    } else if (item?.directBuyingState === "deleted") {
      state = "حذف شده";
    } else {
      state = "در انتظار تایید استان";
    }
    return state;
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.createDate ? formatTime(item?.createDate) : "-",
        item?.reciveDate ? formatJustDate(item?.reciveDate) : "-",
        `${item.killHouse.name} (${item.killHouse.killHouseOperator.user.mobile})`,
        item?.freezing ? "انجماد" : "عادی",
        item?.freeDirectBuying ? "آزاد" : "دولتی",
        item?.slaughterHouse
          ? item?.slaughterHouse?.name
          : item?.killHouse?.name,
        `${item?.poultry?.userprofile?.fullName} (${item?.poultry?.userprofile?.mobile})`,
        item.poultryHatching?.chickenAge || "-",
        `${item.chickenBreed ? item.chickenBreed : "-"}`,
        item.killCapacity?.toLocaleString(),
        item.IndexWeight,
        (item.IndexWeight * item.killCapacity)?.toLocaleString(),
        item?.amount?.toLocaleString(),
        <Grid key={i}>
          {item?.directBuyingState === "pending" &&
          item?.finalAccept === true &&
          (getRoleFromUrl() === "KillHouse" ||
            getRoleFromUrl() === "AdminX" ||
            getRoleFromUrl() === "SuperAdmin" ||
            getRoleFromUrl() === "ProvinceOperator") &&
          poultryCodeMandatory ? (
            <EditVerificationDirectBuy
              updateTable={fetchApiData}
              kill_request_key={item?.key}
              inputDirectBuyingCode={item?.inputDirectBuyingCode}
            />
          ) : (
            <Typography variant="body2">
              {item?.inputDirectBuyingCode || "-"}
            </Typography>
          )}
        </Grid>,
        item?.paymentDeadlineDate
          ? formatJustDate(item?.paymentDeadlineDate)
          : "-",
        getItemState(item),
        item?.directBuyingState === "pending"
          ? "-"
          : item?.automaticAccept
          ? "سیستم"
          : "اپراتور",
        item?.inputDirectBuyingCode ||
        (!item?.freeDirectBuying && item?.directBuyingState === "accepted") ? (
          <SlaughterBuyPdfKillRequest pdf_key={item?.key} />
        ) : (
          "-"
        ),

        <SlaughterFreeBuyOperations
          key={`ops-${i}`}
          item={item}
          updateTable={updateTable}
          poultryCodeMandatory={poultryCodeMandatory}
        />,
      ];
    });

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

  return (
    <Grid container gap={SPACING.SMALL} alignItems="center">
      <Grid container xs={12} px={1} gap={2}>
        <Grid container alignSelf="start">
          {/* {getRoleFromUrl() === "KillHouse" && ( */}
          <Button
            variant="contained"
            onClick={() => {
              dispatch(
                DRAWER({
                  title: "ثبت خرید مستقیم",
                  content: (
                    <SlaughterSubmitFreeBuy
                      updateTable={updateTable}
                      fetchApiData={fetchApiData}
                    />
                  ),
                  right: !(window.innerWidth <= 600),
                  bottom: window.innerWidth <= 600,
                })
              );
            }}
          >
            ثبت خرید مستقیم
          </Button>
          {/* )} */}
        </Grid>
        <Grid container xs={12} justifyContent="start" alignItems="center">
          <Grid
            container
            alignItems="center"
            mb={SPACING.SMALL}
            gap={SPACING.SMALL}
          >
            <form onSubmit={handleSubmit}>
              <Grid container alignItems="center" gap={SPACING.SMALL}>
                <TextField
                  size="small"
                  autoComplete="off"
                  label="جستجو"
                  variant="outlined"
                  style={{ width: 250 }}
                  onChange={handleTextChange}
                />
                <Button
                  // disabled={!textValue}
                  type="submit"
                  onClick={handleSubmit}
                  endIcon={<RiSearchLine />}
                >
                  جستجو
                </Button>
                <Grid container gap={2}>
                  <DatePicker
                    label="از تاریخ"
                    id="date"
                    renderInput={(params) => (
                      <TextField style={{ width: "160px" }} {...params} />
                    )}
                    value={selectedDate1}
                    onChange={(e) => {
                      setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                    }}
                  />
                  <DatePicker
                    label="تا تاریخ"
                    id="date"
                    renderInput={(params) => (
                      <TextField style={{ width: "160px" }} {...params} />
                    )}
                    value={selectedDate2}
                    onChange={(e) => {
                      setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                    }}
                  />
                </Grid>

                <Grid>
                  <Tooltip title="خروجی اکسل">
                    <a
                      href={`${
                        axios.defaults.baseURL
                      }direct_purchase_excel/?date1=${selectedDate1}&date2=${selectedDate2}&role=${getRoleFromUrl()}&key=${userKey}${
                        checkPathStartsWith("slaughter")
                          ? `&role_key=${selectedSubUser?.key || ""}`
                          : ""
                      }`}
                      rel="noreferrer"
                    >
                      <Button color="success">
                        <RiFileExcel2Fill size={32} />
                      </Button>
                    </a>
                  </Tooltip>
                </Grid>
              </Grid>
            </form>
          </Grid>

          <Grid container mt={2} mb={4} isDashboard sx={{ width: "100%" }}>
            <ResponsiveTable
              noPagination
              isDashboard
              columns={[
                "تعداد بارها",
                "تعداد درخواست دولتی",
                "تعداد درخواست آزاد",
                "تعداد بارهای دولتی",
                "تعداد بارهای آزاد",
                "تعداد درخواست (قطعه)",
                "میانگین وزنی",
                "وزن کل (کیلوگرم)",
                "میانگین قیمت فروش مرغدار",
              ]}
              data={[
                [
                  dashboardData?.lenKillRequest?.toLocaleString(),
                  dashboardData?.freeDirectBuyingFalseQuantity?.toLocaleString(),
                  dashboardData?.freeDirectBuyingTrueQuantity?.toLocaleString(),
                  dashboardData?.lenKillRequestHasntFreeDirectBuying?.toLocaleString(),
                  dashboardData?.lenKillRequestHasFreeDirectBuying?.toLocaleString(),
                  dashboardData?.quantity?.toLocaleString(),
                  dashboardData?.indexWight?.toFixed(1),
                  Math.round(
                    dashboardData?.quantity * dashboardData?.indexWight
                  )?.toLocaleString(),
                  Math.round(dashboardData?.amount)?.toLocaleString(),
                ],
              ]}
              title={"خلاصه اطلاعات"}
            />
          </Grid>

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