import React, { useContext, useEffect, useState } from "react";
import { Button, TextField, Tooltip, Typography } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { vetFarmGetDeletedBarsDahsboard } from "../../services/vet-farm-get-deleted-bars-dashboard";

import { Grid } from "../../../../components/grid/Grid";
import { format } from "date-fns-jalali";
import { SPACING } from "../../../../data/spacing";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";
import { formatTime } from "../../../../utils/formatTime";

export const VetFarmDeletedBars = () => {
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [dashboardData, setDashboardData] = useState([]);
  const [dataTableM, setDataTableM] = useState([]);
  const [has500Error, setHas500Error] = useState(false);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const [
    openNotif,
    ,
    selectedDate1,
    setSelectedDate1,
    selectedDate2,
    setSelectedDate2,
  ] = useContext(AppContext);

  const userKey = useSelector((state) => state.userSlice?.userProfile?.key);

  const dispatch = useDispatch();

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

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const fetchApiData = async (page) => {
    // Prevent request if there was a 500 error
    if (has500Error) {
      return;
    }

    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `kill_house_request_bar_management/?check&deleted_requests&search=filter&value=${textValue}&role=${getRoleFromUrl()}${
          checkPathStartsWith("slaughter")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}`
      );
      // Reset error state on successful response
      setHas500Error(false);
      setData(response.data?.results || []);
      setTotalRows(response.data?.count || 0);
    } catch (error) {
      console.error("Error fetching data:", error);
      const errorMessage = error?.message || "";
      const status = error?.response?.status;
      const is500Error = errorMessage.includes("500") || status === 500;

      if (is500Error) {
        setHas500Error(true);
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
          severity: "error",
        });
      }
      setData([]);
      setTotalRows(0);
    } finally {
      dispatch(LOADING_END());
    }
  };

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

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

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

  useEffect(() => {
    // Prevent request if there was a 500 error
    if (has500Error) {
      return;
    }

    fetchApiData(1);
    dispatch(
      vetFarmGetDeletedBarsDahsboard({
        selectedDate1,
        selectedDate2,
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    )
      .then((r) => {
        if (r?.error) {
          const errorMessage = r.error?.message || "";
          const is500Error =
            errorMessage.includes("500") ||
            r.error?.status === 500 ||
            r.error?.statusCode === 500;

          if (is500Error) {
            setHas500Error(true);
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
              severity: "error",
            });
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
              severity: "error",
            });
          }
          setDashboardData([]);
        } else if (r?.payload?.data) {
          // Reset error state on successful response
          setHas500Error(false);
          setDashboardData(r.payload.data);
        } else {
          setDashboardData([]);
        }
      })
      .catch((error) => {
        console.error("Error fetching dashboard data:", error);
        const errorMessage = error?.message || "";
        const status = error?.response?.status;
        const is500Error = errorMessage.includes("500") || status === 500;

        if (is500Error) {
          setHas500Error(true);
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
            severity: "error",
          });
        }
        setDashboardData([]);
      });
  }, [dispatch, selectedDate1, selectedDate2, perPage, selectedSubUser?.key]);

  // Reset error state when dates or filters change
  useEffect(() => {
    setHas500Error(false);
  }, [selectedDate1, selectedDate2, textValue]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    // Reset error state on manual submit (user retry)
    setHas500Error(false);
    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `kill_house_request_bar_management/?check&deleted_requests&search=filter&value=${textValue}&role=${getRoleFromUrl()}${
          checkPathStartsWith("slaughter")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }&date1=${selectedDate1}&date2=${selectedDate2}&page=1&page_size=${perPage}`
      );
      // Reset error state on successful response
      setHas500Error(false);
      setData(response.data?.results || []);
      setTotalRows(response.data?.count || 0);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
      const errorMessage = error?.message || "";
      const status = error?.response?.status;
      const is500Error = errorMessage.includes("500") || status === 500;

      if (is500Error) {
        setHas500Error(true);
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
          severity: "error",
        });
      }
      setData([]);
      setTotalRows(0);
      dispatch(LOADING_END());
    }
  };
  const handleDateChange1 = (date) => {
    setSelectedDate1(date);
  };

  const handleDateChange2 = (date) => {
    setSelectedDate2(date);
  };

  useEffect(() => {
    if (!data || !Array.isArray(data)) {
      setDataTableM([]);
      return;
    }

    const d = data.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.barCode || "",

        item?.vetFarm?.vet?.user?.fullname
          ? item.vetFarm.vet.user.fullname +
            `(${item?.vetFarm?.vet?.user?.mobile || ""})`
          : "فاقد دامپزشک",

        item?.poultryRequest?.freezing ? "انجماد" : "عادی",

        item?.poultryRequest?.freeSaleInProvince ? "آزاد" : "دولتی",

        `${item?.addCar?.driver?.typeCar || ""} ${
          item?.addCar?.driver?.pelak || ""
        }`,

        `${item?.addCar?.driver?.driverName || ""} (${
          item?.addCar?.driver?.driverMobile || ""
        })`,

        `${item?.killhouseUser?.name || ""} (${
          item?.killhouseUser?.killHouseOperator?.user?.mobile || ""
        })`,

        item?.killer
          ? `${item.killer?.name || ""} (${
              item.killer?.killHouseOperator?.user?.mobile || ""
            })`
          : "-",

        `${item?.poultryRequest?.poultry?.unitName || ""} (${
          item?.poultryRequest?.poultry?.user?.mobile || ""
        })`,

        item?.poultryRequest?.poultry?.address?.city?.name || "",
        item?.poultryRequest?.age || "",

        item?.killPlace || "",

        item?.poultryRequest?.amount
          ? item.poultryRequest.amount.toLocaleString() + " ﷼"
          : "0 ﷼",

        item?.weightInfo?.killHousePrice
          ? item.weightInfo.killHousePrice.toLocaleString() + " ﷼"
          : "0 ﷼",

        item?.poultryRequest?.sendDate
          ? (() => {
              try {
                const date = new Date(item.poultryRequest.sendDate);
                return isNaN(date.getTime()) ? "-" : format(date, "yyyy/MM/dd");
              } catch (error) {
                console.error("Error formatting sendDate:", error);
                return "-";
              }
            })()
          : "-",

        item?.poultryRequest?.orderCode || "",

        item?.poultryRequest?.chickenBreed || "",

        item?.quantity ? item.quantity.toLocaleString() : "0",

        item?.trafficCode || "",
        item?.amount ? item.amount.toLocaleString() + " ﷼" : "0 ﷼",
        item?.clearanceCode || "-",
        (item?.nonReceipt && item?.mainNonReceipt ? `کاربر` : "سیستم") +
          " " +
          formatTime(item?.modifyDate),
        item?.nonReceiptMessage || "-",
      ];
    });

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

  const tableTitle = (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      gap={2}
      paddingTop={2}
      mb={1}
    >
      <Grid container alignItems="center" gap={SPACING.SMALL} xs={12}>
        <Typography>بارهای حذف شده</Typography>
        <Grid>
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => <TextField size="small" {...params} />}
            value={selectedDate1}
            onChange={(e) => {
              handleDateChange1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => <TextField size="small" {...params} />}
            value={selectedDate2}
            onChange={(e) => {
              handleDateChange2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>

        <TextField
          autoComplete="off"
          size="small"
          label="جستجو"
          variant="outlined"
          style={{ width: 180 }}
          onChange={handleTextChange}
        />
        <Button
          // disabled={!textValue}
          endIcon={<RiSearchLine />}
          type="submit"
          onClick={handleSubmit}
        >
          جستجو
        </Button>
        {(getRoleFromUrl() === "ProvinceOperator" ||
          getRoleFromUrl() === "SuperAdmin" ||
          getRoleFromUrl() === "AdminX" ||
          getRoleFromUrl() === "Supporter" ||
          getRoleFromUrl() === "CityJahad" ||
          getRoleFromUrl() === "CityPoultry" ||
          getRoleFromUrl() === "KillHouse") && (
          <Tooltip title="خروجی اکسل">
            <a
              href={`${axios.defaults.baseURL}bar_excel_trash_true/?start=${
                selectedDate1 || ""
              }&end=${selectedDate2 || ""}&key=${
                userKey || ""
              }&role=${getRoleFromUrl()}&search=filter&value=${
                textValue || ""
              }${
                checkPathStartsWith("slaughter")
                  ? `&role_key=${selectedSubUser?.key}`
                  : ""
              }`}
              rel="noreferrer"
            >
              <Button color="success">
                <RiFileExcel2Fill size={32} />
              </Button>
            </a>
          </Tooltip>
        )}
      </Grid>
    </Grid>
  );

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        {tableTitle}
        <Grid container mt={2} mb={4} isDashboard xs={12}>
          <ResponsiveTable
            noPagination
            isDashboard
            columns={[
              "تعداد بار",
              "تعداد خریداران",
              "حجم بار",
              "وزن بار",
              "بار های فاقد قرنطینه",
              "بارهای دارای قرنطینه",
            ]}
            data={[
              [
                dashboardData?.lenKillHouseRequest
                  ? dashboardData.lenKillHouseRequest.toLocaleString()
                  : "0",
                dashboardData?.lenKillHouse
                  ? dashboardData.lenKillHouse.toLocaleString()
                  : "0",
                dashboardData?.firstQuantity
                  ? dashboardData.firstQuantity.toLocaleString()
                  : "0",
                dashboardData?.firstWeight
                  ? dashboardData.firstWeight.toLocaleString()
                  : "0",
                dashboardData?.lenHasntCode
                  ? dashboardData.lenHasntCode.toLocaleString()
                  : "0",
                dashboardData?.lenHasCode
                  ? dashboardData.lenHasCode.toLocaleString()
                  : "0",
              ],
            ]}
            title={"خلاصه اطلاعات"}
          />
        </Grid>
        <ResponsiveTable
          data={dataTableM}
          columns={[
            "ردیف",
            "کدبار",
            "دامپزشک فارم",
            "نوع کشتار",
            "نوع فروش",
            "ماشین",
            "راننده",
            "خریدار",
            "کشتارکن اختصاصی",

            "محل کشتار",
            "مرغدار",
            "سن مرغ",
            "شهر",
            "قیمت مرغدار",
            "قیمت کشتارگاه",
            "تاریخ کشتار",
            "کدسفارش کشتار",
            "نژاد",
            "تعداد",
            "کد بهداشتی حمل و نقل",
            "قیمت مرغ زنده‌ی بار",
            "کدرهگیری سامانه قرنطینه",
            "نوع برگشت",
            "پیام عدم دریافت",
          ]}
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
          title="بارهای حذف شده"
        />
      </Grid>
    </Grid>
  );
};
