import React, { useContext, useEffect, useState } from "react";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import { Button, IconButton, Tooltip } from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { formatJustDate } from "../../../../utils/formatTime";
import ShowImage from "../../../../components/show-image/ShowImage";
import { SlaughterHouseVetBarsOperation } from "../../../slaughter-house-vet/components/slaughter-house-vet-bars-operation/SlaughterHouseVetBarsOperation";
import SystemUpdateAltIcon from "@mui/icons-material/SystemUpdateAlt";
import { slaughterGetProfile } from "../../services/slaughter-get-profile";
import { CheckCleanceCode } from "../../../../components/check-clearance-code/ChechClearanceCode";
import { SlaughterFreeBarsAlivesOperations } from "../slaughter-free-bars-alives-operations/SlaughterFreeBarsAlivesOperations";
import { AppContext } from "../../../../contexts/AppContext";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";
import { fetchSlaughterBroadcastAndProducts } from "../../services/handle-fetch-slaughter-products";

export const SlaughterInventoryFreeBuyBarsAlives = ({
  title,
  barState,
  fetchDashboardData,
  withDate,
  selectedDate1,
  selectedDate2,
  searchValue,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  useEffect(() => {
    dispatch(
      slaughterGetProfile({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    );
  }, [selectedSubUser?.key]);

  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [page, setPage] = useState(1);
  const [tableData, setTableData] = useState([]);

  const fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    try {
      response = await axios.get(
        `kill_house_free_bar/?type=live&role=${getRoleFromUrl()}${
          checkPathStartsWith("slaughter")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }&page=${page}&page_size=${perPage}&bar_state=${barState}&date_type=input${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ""
        }${searchValue ? `&search=filter&value=${searchValue}` : ""}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    } 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);
    fetchDashboardData();
    dispatch(
      fetchSlaughterBroadcastAndProducts({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    );
  };

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

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.barCode || "-",
        item?.registerType === "automatic" ? "سیستمی" : "دستی",
        formatJustDate(item.createDate),
        `${item?.killHouse?.name} (${item?.killHouse?.killHouseOperator?.user?.mobile})`,
        item?.exclusiveKiller
          ? `${item?.exclusiveKiller?.name} (${item?.exclusiveKiller?.killHouseOperator?.user?.mobile})`
          : "-",
        item.buyType === "live" ? "مرغ زنده" : "لاشه",
        item.poultryName,
        `${item.province}/${item.city}`,
        <CheckCleanceCode key={i} clearanceCode={item.barClearanceCode} />,
        item.quantity.toLocaleString(),
        item.liveWeight.toLocaleString(),
        formatJustDate(item.date),
        item.numberOfCarcasses.toLocaleString(),
        item.weightOfCarcasses.toLocaleString(),
        item?.weightLoss ? item?.weightLoss + "%" : "-",
        <ShowImage key={i} src={item.barImage} />,
        <>
          {getRoleFromUrl() === "KillHouse" ? (
            <SlaughterFreeBarsAlivesOperations
              key={item.key}
              item={item}
              inventoryKey={item?.key}
              updateTable={updateTable}
              barState={barState}
            />
          ) : (
            <Button
              variant="outlined"
              disabled={item?.killHouseVetState !== "pending"}
              size="small"
              onClick={() => {
                dispatch(
                  OPEN_MODAL({
                    title: "تایید / رد",
                    content: (
                      <SlaughterHouseVetBarsOperation
                        item={item}
                        updateTable={updateTable}
                      />
                    ),
                  })
                );
              }}
            >
              تایید / رد
            </Button>
          )}
        </>,
      ];
    });

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

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

  return (
    <Grid container justifyContent="flex-end" mt={2} mb={2}>
      <Grid
        container
        mt={SPACING.MEDIUM}
        alignItems="end"
        gap={2}
        justifyContent="flex-end"
      >
        <ResponsiveTable
          operation={
            <Grid>
              <Tooltip title="خروجی اکسل" placement="top">
                <IconButton
                  color="primary"
                  onClick={() => {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                      severity: "success",
                    });
                    const link = `${
                      axios.defaults.baseURL
                    }kill_house_free_bar_excel/?role=${getRoleFromUrl()}${
                      checkPathStartsWith("slaughter")
                        ? `&role_key=${selectedSubUser?.key}`
                        : ""
                    }&key=${userKey}&type=live&bar_state=${barState}${
                      withDate
                        ? `&date1=${selectedDate1}&date2=${selectedDate2}`
                        : ""
                    }`;
                    window.location.href = link;
                  }}
                >
                  <SystemUpdateAltIcon />
                </IconButton>
              </Tooltip>
            </Grid>
          }
          data={tableData}
          columns={[
            "ردیف",
            "کد بار",
            "نوع بار",
            "تاریخ خرید",
            "خریدار",
            "کشتارکن",
            "محصول",
            "فروشنده",
            "استان/شهر",
            "کدقرنطینه",
            "حجم زنده",
            "وزن زنده (کیلوگرم)",
            "تاریخ ورود به انبار",
            "حجم لاشه",
            "وزن لاشه (کیلوگرم)",
            "درصد افت",
            "بارنامه",
            "عملیات",
          ]}
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
          title={title}
        />
      </Grid>
    </Grid>
  );
};
