import React, { useContext, useEffect, useState } from "react";
import { Button, Tab, Tabs, TextField, Tooltip } 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 {
  ROUTE_ADMINX_CHAINS,
  ROUTE_PARENT_COMPANY_ALLOCATIONS,
  ROUTE_PROVINCE_CHAINS,
  ROUTE_SUPER_ADMIN_CHAINS,
} from "../../../../routes/routes";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { AppContext } from "../../../../contexts/AppContext";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { useLocation } from "react-router-dom";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { ChainBarManagementEditHealthCode } from "../chain-bar-management-edit-health-code/ChainBarManagementEditHealthCode";
import { ChainBarManagementOperations } from "../chain-bar-management-operations/ChainBarManagementOperations";
import { format } from "date-fns-jalali";
import { ChainSubmitQuarantineCode } from "../chain-submit-quarantine-code/ChainSubmitQuarantineCode";
import { formatJustDate } from "../../../../utils/formatTime";

export const ChainBarManagement = ({ province }) => {
  const [
    openNotif,
    ,
    selectedDate1,
    setSelectedDate1,
    selectedDate2,
    setSelectedDate2,
  ] = useContext(AppContext);
  const dispatch = useDispatch();
  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  const { pathname } = useLocation();

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

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

  const [value, setValue] = useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  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 [tableDataRejected, setTableDataRejected] = useState([]);
  const [has500Error, setHas500Error] = useState(false);

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

    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `${
          province ? province + "parent-company-" : ""
        }chain-allocation/?search=filter&value=${textValue}&page=${page}&page_size=${perPage}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}${
          value === 1 ? "&state=rejected" : ""
        }`
      );
      // 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(() => {
    if (!data || !Array.isArray(data)) {
      setTableData([]);
      setTableDataRejected([]);
      return;
    }

    const d = data.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        <ChainBarManagementOperations
          key={i}
          fetchApiData={updateTable}
          item={item}
        />,
        item?.state === "accepted"
          ? "تایید شده"
          : item?.state === "pending"
          ? "در انتظار تایید"
          : "رد شده",
        item?.date ? formatJustDate(item.date) : "-",
        item?.outProvince ? "خارج استان" : "داخل استان",
        `${item?.registerer?.fullname || ""} (${
          item?.registerer?.mobile || ""
        })`,
        item?.killHouse?.killHouseOperator?.user?.fullname
          ? `${item.killHouse.killHouseOperator.user.fullname} (${
              item?.killHouse?.killHouseOperator?.user?.mobile || ""
            })`
          : `${item?.buyerName || ""} (${item?.buyerMobile || ""})`,
        `${item?.poultryHatching?.poultry?.unitName || ""} (${
          item?.poultryHatching?.poultry?.user?.mobile || ""
        })`,
        `${item?.chainCompany?.name || ""} (${
          item?.chainCompany?.user?.mobile || ""
        })`,
        <>
          {" "}
          {getRoleFromUrl() === "ParentCompany" ? (
            item?.healthCode || ""
          ) : (
            <ChainBarManagementEditHealthCode
              healthCode={item?.healthCode}
              item={item}
              updateTable={updateTable}
            />
          )}
        </>,
        <>
          {getRoleFromUrl() === "VetFarm" ||
          getRoleFromUrl() === "ProvinceOperator" ||
          getRoleFromUrl() === "SuperAdmin" ||
          getRoleFromUrl() === "Supporter" ||
          getRoleFromUrl() === "AdminX" ||
          getRoleFromUrl() === "CityVet" ||
          getRoleFromUrl() === "VetSupervisor" ? (
            <>
              <ChainSubmitQuarantineCode
                isLocked={
                  getRoleFromUrl() === "ProvinceOperator" ||
                  getRoleFromUrl() === "VetSupervisor"
                    ? false
                    : item?.trash === true ||
                      // item.assignmentStateArchive === "True" ||
                      // item.vetState === "accepted" ||
                      item?.quarantineQuantity
                    ? true
                    : false
                }
                item={item}
                updateTable={updateTable}
              />
              {item?.quarantineCodeRegisterar?.date
                ? (() => {
                    try {
                      const date = new Date(item?.registerar?.date);
                      return isNaN(date.getTime())
                        ? ""
                        : `${format(date, "yyyy/MM/dd")} ${
                            item?.quarantineCodeRegisterar?.name || ""
                          }`;
                    } catch (error) {
                      console.error(
                        "Error formatting quarantineCodeRegisterar date:",
                        error
                      );
                      return "";
                    }
                  })()
                : ""}
            </>
          ) : item?.quarantineCode ? (
            item.quarantineCode
          ) : (
            "-"
          )}
        </>,
        item?.driverName
          ? `${item.driverName} (${item?.driverMobile || ""})`
          : "-",
        item?.typeCar || "",
        item?.pelak || "",
        item?.quantity || 0,
        item?.indexWeight || 0,
        item?.weight || 0,
      ];
    });
    setTableData(d);

    const r = data.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.state === "rejected"
          ? "رد شده"
          : item?.state === "deleted"
          ? "حذف شده"
          : "در انتظار تایید",
        item?.remover
          ? `${item.remover?.fullname || ""} (${item.remover?.mobile || ""})`
          : `${item?.registerer?.fullname || ""} (${
              item?.registerer?.mobile || ""
            })`,
        item?.date ? formatJustDate(item.date) : "-",
        item?.outProvince ? "خارج استان" : "داخل استان",
        item?.registerer?.fullname
          ? `${item.registerer.fullname} (${item?.registerer?.mobile || ""})`
          : "-",
        item?.killHouse?.killHouseOperator?.user?.fullname
          ? `${item.killHouse.killHouseOperator.user.fullname} (${
              item?.killHouse?.killHouseOperator?.user?.mobile || ""
            })`
          : `${item?.buyerName || ""} (${item?.buyerMobile || ""})`,
        `${item?.poultryHatching?.poultry?.unitName || ""} (${
          item?.poultryHatching?.poultry?.user?.mobile || ""
        })`,
        `${item?.chainCompany?.name || ""} (${
          item?.chainCompany?.user?.mobile || ""
        })`,
        item?.healthCode || "",
        item?.quarantineCode || "",
        item?.driverName
          ? `${item.driverName} (${item?.driverMobile || ""})`
          : "-",
        item?.typeCar || "",
        item?.pelak || "",
        item?.quantity || 0,
        item?.indexWeight || 0,
        item?.weight || 0,
      ];
    });

    setTableDataRejected(r);
  }, [data, page, perPage]);

  useEffect(() => {
    fetchApiData(1);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dispatch, selectedDate1, selectedDate2, perPage, value]);

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

  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(
        `${
          province ? province + "parent-company-" : ""
        }chain-allocation/?search=filter&value=${textValue}&page=${page}&page_size=${perPage}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}${
          value === 1 ? "&state=rejected" : ""
        }`
      );
      // 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 tableTitle = (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      gap={2}
      paddingTop={2}
      mb={1}
      xs={12}
    >
      <Grid container alignItems="center" gap={SPACING.SMALL}>
        <Grid style={{ width: "150px" }}>
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => <TextField {...params} />}
            value={selectedDate1}
            onChange={(e) => {
              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid style={{ width: "150px" }}>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => <TextField {...params} />}
            value={selectedDate2}
            onChange={(e) => {
              setSelectedDate2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </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>
          {value === 0 ? (
            <Tooltip title="خروجی اکسل">
              <a
                href={`${
                  province ? province : axios.defaults.baseURL
                }bar_chain_excel/?key=${
                  userKey || ""
                }&role=${getRoleFromUrl()}&search=filter&value=${
                  textValue || ""
                }&state=accepted&date1=${selectedDate1 || ""}&date2=${
                  selectedDate2 || ""
                }&search=filter&value=${textValue || ""}`}
                rel="noreferrer"
              >
                <Button color="success">
                  <RiFileExcel2Fill size={32} />
                </Button>
              </a>
            </Tooltip>
          ) : (
            <Tooltip title="خروجی اکسل">
              <a
                href={`${
                  province ? province : axios.defaults.baseURL
                }bar_chain_excel/?key=${
                  userKey || ""
                }&role=${getRoleFromUrl()}&search=filter&value=${
                  textValue || ""
                }&state=rejected&date1=${selectedDate1 || ""}&date2=${
                  selectedDate2 || ""
                }&search=filter&value=${textValue || ""}`}
                rel="noreferrer"
              >
                <Button color="success">
                  <RiFileExcel2Fill size={32} />
                </Button>
              </a>
            </Tooltip>
          )}
        </form>
      </Grid>
    </Grid>
  );

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid xs={12} container justifyContent="center" alignItems="center">
        {(pathname === ROUTE_PROVINCE_CHAINS ||
          pathname === ROUTE_SUPER_ADMIN_CHAINS ||
          pathname === ROUTE_ADMINX_CHAINS ||
          pathname === ROUTE_PARENT_COMPANY_ALLOCATIONS) && (
          <Tabs
            value={value}
            onChange={handleChange}
            aria-label="simple tabs example"
          >
            <Tab label="درخواست های تایید شده" />
            <Tab label="درخواست های رد شده" />
          </Tabs>
        )}
      </Grid>

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