import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { Button, TextField, Tooltip } from "@mui/material";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { DatePicker } from "@mui/x-date-pickers";
import { AppContext } from "../../../../contexts/AppContext";
import { stawardGetOutDashboardService } from "../../../guild/services/steward-get-out-dashboard";
import moment from "moment";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { formatJustDate } from "../../../../utils/formatTime";
import ShowImage from "../../../../components/show-image/ShowImage";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { StewardSellOutOperations } from "../steward-buy-out-operations/StewardSellOutOperations";
import { StewardSubmitFreeBar } from "../steward-submit-free-bar/StewardSubmitFreeBar";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const StewardPurchaseOutProvince = ({ isBarManagemen }) => {
  const [data, setData] = useState([]);

  const [tableData, setTableData] = 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 [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  //   const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

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

  const getDashboardData = () => {
    dispatch(
      stawardGetOutDashboardService({
        date1: selectedDate1,
        date2: selectedDate2,
        search: "filter",
        role_key: checkPathStartsWith("steward")
          ? selectedSubUser?.key || ""
          : "",
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `steward_free_bar/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&role=${getRoleFromUrl()}${
        checkPathStartsWith("steward")
          ? `&role_key=${selectedSubUser?.key}`
          : ""
      }`
    );

    getDashboardData();
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

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

  // Fetch data when dates or perPage change (only if dates are set)
  useEffect(() => {
    if (selectedDate1 && selectedDate2) {
    fetchApiData(1);
      setPage(1);
    }
  }, [selectedDate1, selectedDate2, perPage]);

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

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

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

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        formatJustDate(item.createDate),
        `${item?.killHouseName} (${item?.killHouseMobile})`,
        item?.product?.name?.toLocaleString() || "-",
        item?.killHouseName?.toLocaleString(),
        `${item?.city} (${item?.province})`,
        item?.numberOfCarcasses?.toLocaleString() || "-",
        item?.weightOfCarcasses?.toLocaleString() || "-",
        <ShowImage key={i} src={item?.barImage} />,

        <StewardSellOutOperations
          key={i}
          item={item}
          updateTable={updateTable}
        />,
      ];
    });

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `steward_free_bar/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&role=${getRoleFromUrl()}${
          checkPathStartsWith("steward")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      getDashboardData();
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <Grid container direction="column" flexWrap="nowrap" mt={SPACING.SMALL}>
      <Grid
        container
        mt={SPACING.MEDIUM}
        alignItems="center"
        justifyContent="center"
        gap={2}
      >
        <form onSubmit={handleSubmit}>
          <Grid container alignItems="center" gap={SPACING.SMALL}>
            {getRoleFromUrl() === "Steward" && !isBarManagemen && (
              <Button
                variant="contained"
                onClick={() => {
                  dispatch(
                    DRAWER({
                      right: !(window.innerWidth <= 600),
                      bottom: window.innerWidth <= 600,
                      title: "ثبت اطلاعات خرید",
                      content: (
                        <StewardSubmitFreeBar
                          selectedDate={selectedDate1}
                          updateTable={updateTable}
                        />
                      ),
                    })
                  );
                }}
              >
                ثبت اطلاعات خرید
              </Button>
            )}

            <TextField
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              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"))
                }
              />
            </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("steward")
                      ? `&role_key=${selectedSubUser?.key}`
                      : ""
                  }&key=${userKey}&date1=${selectedDate1}&date2=${selectedDate2}&type=carcass&search=filter&value=${textValue}&date_type=buy`;
                  window.location.href = link;
                }}
              >
                <RiFileExcel2Fill size={32} />
              </Button>
            </Tooltip>
          </Grid>
        </form>

        <Grid container mt={2} mb={4} isDashboard xs={12}>
          <ResponsiveTable
            noPagination
            isDashboard
            columns={["تعداد کل بارها", "تعداد کل", "وزن کل (کیلوگرم)"]}
            data={[
              [
                dashboardData?.totalBars?.toLocaleString() || "0",
                dashboardData?.totalQuantity?.toLocaleString() || "0",
                dashboardData?.totalWeight?.toLocaleString() || "0",
              ],
            ]}
            title={"خلاصه اطلاعات"}
          />
        </Grid>

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