import React, { useContext, useEffect, useState } from "react";
import moment from "moment";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import {
  Button,
  IconButton,
  Tab,
  Tabs,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import {
  CLOSE_MODAL,
  DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { AppContext } from "../../../../contexts/AppContext";
import { SlaughterFreeBarsOperations } from "../slaughter-free-bars-operations/SlaughterFreeBarsOperations";
import { formatJustDate } from "../../../../utils/formatTime";
import ShowImage from "../../../../components/show-image/ShowImage";
import { SlaughterSubmitFreeBar } from "../slaughter-submit-free-bar/SlaughterSubmitFreeBar";
import { SlaughterHouseVetBarsOperation } from "../../../slaughter-house-vet/components/slaughter-house-vet-bars-operation/SlaughterHouseVetBarsOperation";
import { RiFileExcel2Fill } from "react-icons/ri";
import { slaughterGetProfile } from "../../services/slaughter-get-profile";
import { vetFarmGetOutProvinceDashboard } from "../../../vet-farm/services/vet-farm-get-out-province-dashboard";
import { RiSearchLine } from "react-icons/ri";
import { CheckCleanceCode } from "../../../../components/check-clearance-code/ChechClearanceCode";
import { slaughterDeleteInventoryFreeBarService } from "../../services/slaughter-delete-inventory-free-bar";
import { slaughterReturnEnteredFreeBarService } from "../../services/slaughter-return-entered-free-bar";
import DeleteIcon from "@mui/icons-material/Delete";
import UndoIcon from "@mui/icons-material/Undo";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterFreeBuyBars = ({ isBarManagemen }) => {
  const [activeTab, setActiveTab] = useState(0);
  const [tableDataArchive, setTableDataArchive] = useState([]);
  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 [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  const [dashboardData, setDashboardData] = useState([]);
  const handleTabChange = (event, newValue) => {
    setActiveTab(newValue);
  };

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const getDashboardData = () => {
    dispatch(
      vetFarmGetOutProvinceDashboard({
        date1: selectedDate1,
        date2: selectedDate2,
        search: "filter",
        role: getRoleFromUrl(),
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
        value: textValue,
        type: activeTab === 0 ? "live" : "carcass",
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

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

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

  const { inventorySelectedKillHouse } = useSelector(
    (state) => state.slaughterSlice
  );

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

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `kill_house_free_bar/?type=${
        activeTab === 0 ? "live" : "carcass"
      }&search=filter&value=${textValue}&role=${getRoleFromUrl()}${
        checkPathStartsWith("slaughter")
          ? `&role_key=${selectedSubUser?.key}`
          : ""
      }&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&date_type=buy`
    );
    getDashboardData();
    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 = () => {
    setPage(1);
    fetchApiData(1);
    getDashboardData();
  };

  useEffect(() => {
    fetchApiData(1);
  }, [selectedSubUser?.key]);

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.registerType === "automatic" ? "سیستمی" : "دستی",
        item?.barCode || "-",
        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={item?.key}
          clearanceCode={item?.barClearanceCode}
        />,
        item.car || "-",
        item?.driverName || "-",

        item?.driverMobile || "-",
        formatJustDate(item.date),

        item.numberOfCarcasses.toLocaleString(),
        item.weightOfCarcasses.toLocaleString(),
        <ShowImage key={i} src={item.barImage} />,
        <>
          {getRoleFromUrl() === "KillHouse" ? (
            <SlaughterFreeBarsOperations
              key={item.key}
              item={item}
              inventoryKey={item?.key}
              updateTable={updateTable}
            />
          ) : (
            <Button
              variant="outlined"
              disabled={item?.killHouseVetState !== "pending"}
              size="small"
              onClick={() => {
                dispatch(
                  OPEN_MODAL({
                    title: "تایید / رد",
                    content: (
                      <SlaughterHouseVetBarsOperation
                        item={item}
                        updateTable={updateTable}
                      />
                    ),
                  })
                );
              }}
            >
              تایید / رد
            </Button>
          )}
        </>,
      ];
    });

    setTableData(d);

    const getInformation = (item) => {
      if (getRoleFromUrl() === "AdminX" || getRoleFromUrl() === "SuperAdmin") {
        return [
          <Tooltip
            key={item}
            title="بازگشت بار"
            placement="top"
            disableHoverListener={
              !(
                item?.weightOfCarcasses &&
                item?.enteredMessage === "ورود به انبار مجازی"
              )
            }
          >
            <span>
              <IconButton
                color="primary"
                size="small"
                disabled={
                  !(
                    item?.weightOfCarcasses &&
                    item?.enteredMessage === "ورود به انبار مجازی"
                  )
                }
                onClick={() => {
                  dispatch(
                    OPEN_MODAL({
                      title: "بازگشت بار",
                      content: (
                        <Grid
                          container
                          xs={12}
                          justifyContent="center"
                          alignItems="center"
                        >
                          <Typography variant="body2" color="red">
                            آیا از بازگشت بار از انبار اطمینان دارید؟
                          </Typography>
                          <Grid
                            container
                            xs={12}
                            mt={2}
                            justifyContent="center"
                            alignItems="center"
                            spacing={2}
                          >
                            <Grid item xs={6}>
                              <Button
                                onClick={() => {
                                  dispatch(
                                    slaughterReturnEnteredFreeBarService({
                                      key: item.key,
                                      return_entered_bar: true,
                                    })
                                  ).then((r) => {
                                    if (r.payload.error) {
                                      openNotif({
                                        vertical: "top",
                                        horizontal: "center",
                                        msg: r.payload.error,
                                        severity: "error",
                                      });
                                    } else {
                                      openNotif({
                                        vertical: "top",
                                        horizontal: "center",
                                        msg: "عملیات با موفقیت انجام شد.",
                                        severity: "success",
                                      });
                                      updateTable();
                                      dispatch(CLOSE_MODAL());
                                    }
                                  });
                                }}
                                variant="contained"
                                color="error"
                                fullWidth
                              >
                                تایید
                              </Button>
                            </Grid>
                            <Grid item xs={6}>
                              <Button
                                variant="contained"
                                color="primary"
                                fullWidth
                                onClick={() => dispatch(CLOSE_MODAL())}
                              >
                                لغو
                              </Button>
                            </Grid>
                          </Grid>
                        </Grid>
                      ),
                    })
                  );
                }}
              >
                <UndoIcon fontSize="small" />
              </IconButton>
            </span>
          </Tooltip>,
        ];
      } else {
        return [];
      }
    };

    const a = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.registerType === "automatic" ? "سیستمی" : "دستی",
        item?.barCode || "-",
        formatJustDate(item.createDate),
        formatJustDate(item.registerDate) || "-",
        `${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}
          bar_key={item?.key}
          register_type={item?.registerType}
          clearanceCode={item?.barClearanceCode}
        />,
        item.car || "-",
        item?.driverName || "-",
        item?.driverMobile || "-",
        item.quantity.toLocaleString(),
        item.liveWeight.toLocaleString(),
        formatJustDate(item.date),

        item.numberOfCarcasses.toLocaleString(),
        item.weightOfCarcasses.toLocaleString(),
        item?.poultry?.age,
        item.weightOfCarcasses ? "ورود به انبار" : "در انتظار ورود به انبار",
        <ShowImage key={i} src={item.barImage} />,
        ...getInformation(item),
        <>
          {getRoleFromUrl() === "KillHouse" ? (
            <SlaughterFreeBarsOperations
              key={item.key}
              item={item}
              inventoryKey={item?.key}
              updateTable={updateTable}
            />
          ) : (
            isBarManagemen &&
            getRoleFromUrl() === "AdminX" && (
              <Tooltip title="حذف بار" placement="top">
                <IconButton
                  color="error"
                  size="small"
                  onClick={() => {
                    dispatch(
                      OPEN_MODAL({
                        title: "حذف بار",
                        content: (
                          <Grid
                            container
                            xs={12}
                            justifyContent="center"
                            alignItems="center"
                          >
                            <Typography variant="body2" color="red">
                              آیا از حذف بار اطمینان دارید؟
                            </Typography>
                            <Grid
                              container
                              xs={12}
                              mt={2}
                              justifyContent="center"
                              alignItems="center"
                              spacing={2}
                            >
                              <Grid item xs={6}>
                                <Button
                                  onClick={() => {
                                    dispatch(
                                      slaughterDeleteInventoryFreeBarService(
                                        item.key
                                      )
                                    ).then((r) => {
                                      if (r.payload.error) {
                                        openNotif({
                                          vertical: "top",
                                          horizontal: "center",
                                          msg: r.payload.error,
                                          severity: "error",
                                        });
                                      } else {
                                        openNotif({
                                          vertical: "top",
                                          horizontal: "center",
                                          msg: "عملیات با موفقیت انجام شد.",
                                          severity: "success",
                                        });
                                        updateTable();
                                        dispatch(CLOSE_MODAL());
                                      }
                                    });
                                  }}
                                  variant="contained"
                                  color="error"
                                  fullWidth
                                >
                                  تایید
                                </Button>
                              </Grid>
                              <Grid item xs={6}>
                                <Button
                                  variant="contained"
                                  color="primary"
                                  fullWidth
                                  onClick={() => dispatch(CLOSE_MODAL())}
                                >
                                  لغو
                                </Button>
                              </Grid>
                            </Grid>
                          </Grid>
                        ),
                      })
                    );
                  }}
                >
                  <DeleteIcon fontSize="small" />
                </IconButton>
              </Tooltip>
            )
          )}
        </>,
      ];
    });

    setTableDataArchive(a);
  }, [data]);

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

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

    try {
      const response = await axios.get(
        `kill_house_free_bar/?type=${
          activeTab === 0 ? "live" : "carcass"
        }&role=${getRoleFromUrl()}${
          checkPathStartsWith("slaughter")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}&date_type=buy`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      getDashboardData();
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const getLastItem = () => {
    let item = [];
    if (isBarManagemen && getRoleFromUrl() === "AdminX") {
      item = ["حذف"];
    } else if (isBarManagemen) {
      item = [];
    } else {
      item = ["عملیات"];
    }

    return item;
  };

  const information = () => {
    if (getRoleFromUrl() === "AdminX" || getRoleFromUrl() === "SuperAdmin") {
      return ["بازگشت از انبار"];
    } else {
      return [];
    }
  };
  const LiveBars = (
    <ResponsiveTable
      data={tableDataArchive}
      columns={[
        "ردیف",
        "نوع بار",
        "کد بار",
        "تاریخ خرید",
        "تاریخ ثبت در سامانه",
        "خریدار",
        "کشتارکن",
        "محصول",
        "فروشنده",
        "استان/شهر",
        "کدقرنطینه",
        "پلاک ماشین",
        "نام راننده",
        "تلفن راننده",
        "حجم زنده",
        "وزن زنده (کیلوگرم)",
        "تاریخ ورود به انبار",
        "حجم لاشه",
        "وزن لاشه (کیلوگرم)",
        "سن مرغ",
        "وضعیت",
        "بارنامه",
        ...information(),
        ...getLastItem(),
      ]}
      handlePageChange={handlePageChange}
      totalRows={totalRows}
      page={page}
      perPage={perPage}
      handlePerRowsChange={handlePerRowsChange}
      title="بار زنده خرید خارج استان"
    />
  );

  return (
    <Grid
      container
      direction="column"
      flexWrap="nowrap"
      mt={SPACING.SMALL}
      xs={12}
    >
      <Grid
        container
        justifyContent="center"
        alignItems="center"
        my={SPACING.SMALL}
      >
        <Tabs
          scrollButtons="auto"
          variant="scrollable"
          allowScrollButtonsMobile
          value={activeTab}
          onChange={handleTabChange}
        >
          <Tab label="زنده" />
          <Tab label="لاشه" />
        </Tabs>
      </Grid>
      <Grid
        container
        mt={SPACING.MEDIUM}
        alignItems="center"
        justifyContent="center"
        gap={2}
      >
        <form onSubmit={handleSubmit}>
          <Grid container alignItems="center" gap={SPACING.SMALL}>
            {getRoleFromUrl() === "KillHouse" &&
              !isBarManagemen &&
              inventorySelectedKillHouse && (
                <Button
                  // disabled={!slaughterGetInventoryStockData}
                  variant="contained"
                  onClick={() => {
                    dispatch(
                      DRAWER({
                        right: !(window.innerWidth <= 600),
                        bottom: window.innerWidth <= 600,
                        title: "ثبت اطلاعات خرید",
                        content: (
                          <SlaughterSubmitFreeBar
                            selectedDate={selectedDate1}
                            updateTable={updateTable}
                          />
                        ),
                      })
                    );
                  }}
                >
                  ثبت اطلاعات خرید
                </Button>
              )}

            <TextField
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
            <Grid>
              <DatePicker
                label="از تاریخ"
                id="date"
                renderInput={(params) => (
                  <TextField style={{ width: "160px" }} {...params} />
                )}
                value={selectedDate1}
                onChange={(e) => {
                  setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                }}
              />
            </Grid>
            <Grid>
              <DatePicker
                label="تا تاریخ"
                id="date"
                renderInput={(params) => (
                  <TextField style={{ width: "160px" }} {...params} />
                )}
                value={selectedDate2}
                onChange={(e) => {
                  setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                }}
              />
            </Grid>
            <Tooltip title="خروجی اکسل">
              <Button
                color="success"
                onClick={() => {
                  const link = `${
                    axios.defaults.baseURL
                  }kill_house_free_bar_excel/?role=${getRoleFromUrl()}${
                    checkPathStartsWith("slaughter")
                      ? `&role_key=${selectedSubUser?.key}`
                      : ""
                  }&key=${userKey}&date1=${selectedDate1}&date2=${selectedDate2}&type=${
                    activeTab === 0 ? "live" : "carcass"
                  }&search=filter&value=${textValue}&date_type=buy`;
                  window.location.href = link;
                }}
              >
                <RiFileExcel2Fill size={32} />
              </Button>
              {/* </a> */}
            </Tooltip>
          </Grid>
        </form>

        <Grid container mt={2} mb={4} isDashboard xs={12}>
          {activeTab === 0 ? (
            <ResponsiveTable
              noPagination
              columns={[
                "تعداد کل بارهای زنده",
                "حجم کل بارهای زنده",
                "وزن کل بارهای زنده",
                "تعداد کل بارها وارد شده به انبار",
                "حجم کل بارهای زنده وارد شده به انبار",
                "وزن کل بارهای زنده وارد شده به انبار",
                "وزن لاشه بارهای وارد شده به انبار",
                "تعداد کل بارها وارد نشده به انبار",
                "حجم کل بارهای زنده وارد نشده به انبار",
                "وزن کل بارهای زنده وارد نشده به انبار",
              ]}
              data={[
                [
                  dashboardData?.totalBars?.toLocaleString(),
                  dashboardData?.totalBarsQuantity?.toLocaleString(),
                  dashboardData?.totalBarsLiveWeight?.toLocaleString(),
                  dashboardData?.enteredTotalBars?.toLocaleString(),
                  dashboardData?.enteredTotalBarsQuantity?.toLocaleString(),
                  dashboardData?.enteredTotalBarsLiveWeight?.toLocaleString(),
                  dashboardData?.enteredTotalBarsWeightOfCarcasses?.toLocaleString(),
                  dashboardData?.notEnteredTotalBars?.toLocaleString(),
                  dashboardData?.notEnteredTotalBarsQuantity?.toLocaleString(),
                  dashboardData?.notEnteredTotalBarsLiveWeight?.toLocaleString(),
                ],
              ]}
              customColors={[
                {
                  name: "وزن لاشه بارهای وارد شده به انبار",
                  color: "green",
                },
              ]}
              title={"خلاصه اطلاعات"}
            />
          ) : (
            <Grid container xs={12}>
              <ResponsiveTable
                noPagination
                isDashboard
                customWidth={"85vw"}
                columns={["تعداد کل بارها", "حجم لاشه", "وزن لاشه"]}
                data={[
                  [
                    dashboardData?.totalBars?.toLocaleString(),
                    dashboardData?.totalBarsNumberOfCarcasses?.toLocaleString(),
                    dashboardData?.totalBarsWeightOfCarcasses?.toLocaleString(),
                  ],
                ]}
                title={"خلاصه اطلاعات"}
              />
            </Grid>
          )}
        </Grid>

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