import React, { useContext, useEffect, useState } from "react";
import moment from "moment";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import { Button, Checkbox, Tab, Tabs, TextField, Tooltip } 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 {
  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, RiSearchLine } from "react-icons/ri";
import { slaughterGetProfile } from "../../services/slaughter-get-profile";
import { vetFarmGetOutProvinceDashboard } from "../../../vet-farm/services/vet-farm-get-out-province-dashboard";
import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";
import { SlaughterInventoryFreeBuyBarsAlives } from "../slaughter-inventory-free-buy-bars-alives/SlaughterInventoryFreeBuyBarsAlives";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";
import { fetchSlaughterBroadcastAndProducts } from "../../services/handle-fetch-slaughter-products";

export const SlaughterInventoryFreeBuyBars = () => {
  const dispatch = useDispatch();
  const [activeTab, setActiveTab] = useState(0);
  const handleTabChange = (event, newValue) => {
    setActiveTab(newValue);
  };
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

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

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

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

  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 [withDate, setWithDate] = useState(false);
  const [searchValue, setSearchValue] = useState("");
  const [aliveTablesRefreshTrigger, setAliveTablesRefreshTrigger] = useState(0);

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

  const fetchDashboardData = () => {
    dispatch(
      vetFarmGetOutProvinceDashboard({
        search: "filter",
        role: getRoleFromUrl(),
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
        value: searchValue,
        type: activeTab === 0 ? "live" : "carcass",
        ...(withDate && {
          date1: selectedDate1,
          date2: selectedDate2
        })
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  useEffect(() => {
    fetchApiData(page !== 0 ? page : 1);
    fetchDashboardData();
  }, [
    withDate,
    selectedDate1,
    selectedDate2,
    perPage,
    activeTab,
    searchValue,
    selectedSubUser?.key
  ]);

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        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}`,
        item.barClearanceCode,
        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}
              type="carcass"
            />
          ) : (
            <Button
              variant="outlined"
              disabled={item?.killHouseVetState !== "pending"}
              size="small"
              onClick={() => {
                dispatch(
                  OPEN_MODAL({
                    title: "تایید / رد",
                    content: (
                      <SlaughterHouseVetBarsOperation
                        item={item}
                        updateTable={updateTable}
                      />
                    )
                  })
                );
              }}
            >
              تایید / رد
            </Button>
          )}
        </>
      ];
    });

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    setSearchValue(textValue);
  };

  const userKey = useSelector((state) => state.userSlice.userProfile.key);
  const [dashboardData, setDashboardData] = useState([]);

  return (
    <Grid container direction="column" flexWrap="nowrap">
      <Grid container justifyContent="center" alignItems="center">
        <Tabs
          scrollButtons="auto"
          variant="scrollable"
          allowScrollButtonsMobile
          value={activeTab}
          onChange={handleTabChange}
        >
          <Tab label="زنده" />
          <Tab label="لاشه" />
        </Tabs>
      </Grid>
      {activeTab === 0 && (
        <Grid
          mt={2}
          container
          xs={12}
          justifyContent="start"
          alignItems="center"
          gap={2}
        >
          <Grid
            container
            gap={1}
            style={{
              borderStyle: "solid",
              borderWidth: "1px",
              padding: "5px",
              borderRadius: "15px",
              borderColor: "gray",
              justifyContent: "left"
            }}
            alignItems="center"
          >
            <Checkbox
              icon={<ToggleOffOutlinedIcon />}
              checkedIcon={<ToggleOnIcon />}
              checked={withDate}
              onChange={() => {
                setWithDate(!withDate);
                fetchApiData(1);
              }}
              color="primary"
              size="large"
            />
            <Grid>
              <DatePicker
                disabled={!withDate}
                label="از تاریخ"
                id="date"
                renderInput={(params) => (
                  <TextField
                    size="small"
                    style={{ width: "160px" }}
                    {...params}
                  />
                )}
                value={selectedDate1}
                onChange={(e) => {
                  setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                }}
              />
            </Grid>
            <Grid>
              <DatePicker
                disabled={!withDate}
                label="تا تاریخ"
                id="date"
                renderInput={(params) => (
                  <TextField
                    size="small"
                    style={{ width: "160px" }}
                    {...params}
                  />
                )}
                value={selectedDate2}
                onChange={(e) => {
                  setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                }}
              />
            </Grid>
            <Grid>
              <form onSubmit={handleSubmit}>
                <TextField
                  id="outlined-basic"
                  size="small"
                  label="جستجو"
                  variant="outlined"
                  style={{ width: 250 }}
                  value={textValue}
                  onChange={handleTextChange}
                />
                <Button
                  type="submit"
                  onClick={handleSubmit}
                  endIcon={<RiSearchLine />}
                >
                  جستجو
                </Button>
              </form>
            </Grid>
          </Grid>
        </Grid>
      )}
      <Grid
        container
        mt={SPACING.MEDIUM}
        alignItems="center"
        justifyContent="center"
        gap={2}
      >
        <Grid
          container
          alignItems="center"
          gap={SPACING.SMALL}
          justifyContent="start"
          xs={12}
        >
          <Button
            variant="contained"
            onClick={() => {
              dispatch(
                DRAWER({
                  right: !(window.innerWidth <= 600),
                  bottom: window.innerWidth <= 600,
                  title: "ثبت اطلاعات خرید",
                  content: (
                    <SlaughterSubmitFreeBar
                      inventoryKey={"slaughterGetInventoryStockData?.key"}
                      selectedDate={selectedDate1}
                      updateTable={updateTable}
                    />
                  )
                })
              );
            }}
          >
            ثبت اطلاعات خرید
          </Button>
        </Grid>

        <Grid container 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={"خلاصه اطلاعات"}
            />
          ) : (
            <ResponsiveTable
              noPagination
              isDashboard
              columns={["تعداد کل بارها", "حجم لاشه", "وزن لاشه"]}
              data={[
                [
                  dashboardData?.totalBars?.toLocaleString(),
                  dashboardData?.totalBarsNumberOfCarcasses?.toLocaleString(),
                  dashboardData?.totalBarsWeightOfCarcasses?.toLocaleString()
                ]
              ]}
              title={"خلاصه اطلاعات"}
            />
          )}
        </Grid>

        {activeTab === 0 ? (
          <>
            <SlaughterInventoryFreeBuyBarsAlives
              title={"بار زنده در انتظار ورود به انبار (خارج استان)"}
              barState={"notentered"}
              handleUpdate={updateTable}
              refreshTrigger={aliveTablesRefreshTrigger}
              searchValue={searchValue}
              withDate={withDate}
              selectedDate1={selectedDate1}
              selectedDate2={selectedDate2}
            />

            <SlaughterInventoryFreeBuyBarsAlives
              title={"بار زنده وارد شده به انبار (خارج استان)"}
              barState={"entered"}
              handleUpdate={updateTable}
              refreshTrigger={aliveTablesRefreshTrigger}
              searchValue={searchValue}
              withDate={withDate}
              selectedDate1={selectedDate1}
              selectedDate2={selectedDate2}
            />
          </>
        ) : (
          <>
            <form onSubmit={handleSubmit}>
              <Grid container alignItems="center" gap={SPACING.SMALL}>
                <TextField
                  size="small"
                  autoComplete="off"
                  label="جستجو"
                  variant="outlined"
                  style={{ width: 250 }}
                  value={textValue}
                  onChange={handleTextChange}
                />
                <Button
                  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"));
                    }}
                    disabled={!withDate}
                  />
                </Grid>
                <Grid>
                  <DatePicker
                    label="تا تاریخ"
                    id="date"
                    renderInput={(params) => (
                      <TextField style={{ width: "160px" }} {...params} />
                    )}
                    value={selectedDate2}
                    onChange={(e) => {
                      setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                    }}
                    disabled={!withDate}
                  />
                </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}${
                        withDate
                          ? `&date1=${selectedDate1}&date2=${selectedDate2}`
                          : ""
                      }&type=${
                        activeTab === 0 ? "live" : "carcass"
                      }&search=filter&value=${searchValue}&date_type=input`;
                      window.location.href = link;
                    }}
                  >
                    <RiFileExcel2Fill size={32} />
                  </Button>
                </Tooltip>
              </Grid>
            </form>
            <ResponsiveTable
              data={tableData}
              columns={[
                "ردیف",
                "کد بار",
                "تاریخ خرید",
                "خریدار",
                "کشتارکن",
                "محصول",
                "فروشنده",
                "استان/شهر",
                "کدقرنطینه",
                "حجم لاشه",
                "وزن لاشه (کیلوگرم)",
                "بارنامه",
                "عملیات"
              ]}
              handlePageChange={handlePageChange}
              totalRows={totalRows}
              page={page}
              perPage={perPage}
              handlePerRowsChange={handlePerRowsChange}
              title="بار لاشه خرید خارج استان"
            />
          </>
        )}
      </Grid>
    </Grid>
  );
};
