import React, { useContext, useEffect, useState } from "react";
import { Button, 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 ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { AppContext } from "../../../../contexts/AppContext";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import { slaughterSellCarcassOutProvinceGetDashboard } from "../../services/slaughter-sell-carcass-out-province";
import { RiFileExcel2Fill } from "react-icons/ri";
import { SlaughterSellCarcassOutProvinceSellSubmitSell } from "../slaughter-sell-carcass-out-province-submit-sell/SlaughterSellCarcassOutProvinceSellSubmitSell";
import { RiSearchLine } from "react-icons/ri";
import { CheckCleanceCode } from "../../../../components/check-clearance-code/ChechClearanceCode";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import { SlaughterOutProvinceRegistrationCodeInput } from "../slaughter-out-province-registration-code-input/SlaughterOutProvinceRegistrationCodeInput";
import { SlaughterOutProvinceSalesOperations } from "../slaughter-out-province-sales-operations/SlaughterOutProvinceSalesOperations";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";
import { fetchSlaughterBroadcastAndProducts } from "../../services/handle-fetch-slaughter-products";

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

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

  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 fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `kill_house_free_sale_bar/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${
        checkPathStartsWith("slaughter")
          ? `&role_key=${selectedSubUser?.key}`
          : ""
      }&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&type=dashboard`
    );
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

  // const [openNotif] = useContext(AppContext);

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

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

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

  const updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
    dispatch(
      fetchSlaughterBroadcastAndProducts({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    );
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.date ? formatTime(item?.date) : "-",
        item?.productionDate ? formatJustDate(item?.productionDate) : "-",
        (item?.distributionType === "web"
          ? "سایت"
          : item?.distributionType === "app"
          ? "موبایل"
          : item?.distributionType === "pos"
          ? "پوز"
          : item?.distributionType) || "-",
        `${item?.buyerName} (${item?.buyerMobile})`,
        item?.buyer ? `${item?.buyer?.unitName}` : `${item?.buyerName}`,
        item?.province,
        item?.city,
        // item?.numberOfCarcasses?.toLocaleString(),
        item?.clearanceCode && (
          <CheckCleanceCode clearanceCode={item?.clearanceCode} />
        ),
        item?.quarantineWeightOfCarcasses?.toLocaleString(),
        item?.weightOfCarcasses?.toLocaleString(),
        item?.quota === "governmental"
          ? "دولتی"
          : item?.quota === "free"
          ? "آزاد"
          : "-",
        item?.saleType === "governmental"
          ? "دولتی"
          : item?.saleType === "free"
          ? "آزاد"
          : "-",
        item?.systemRegistrationCode ? (
          item?.loggedRegistrationCode ? (
            "تایید شده"
          ) : item?.registrationCode ? (
            <SlaughterOutProvinceRegistrationCodeInput
              key={i}
              item={item}
              fetchApiData={() => fetchApiData(page)}
            />
          ) : (
            "-"
          )
        ) : (
          "-"
        ),
        <SlaughterOutProvinceSalesOperations
          key={i}
          item={item}
          updateTable={updateTable}
          fetchApiData={fetchApiData}
          page={page}
        />,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `kill_house_free_sale_bar/?role=${getRoleFromUrl()}${
          checkPathStartsWith("slaughter")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}&type=dashboard`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
    dispatch(
      slaughterSellCarcassOutProvinceGetDashboard({
        selectedDate1,
        selectedDate2,
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  const [dashboardData, setDashboardData] = useState([]);

  useEffect(() => {
    dispatch(
      slaughterSellCarcassOutProvinceGetDashboard({
        selectedDate1,
        selectedDate2,
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  }, [selectedDate1, selectedDate2, selectedSubUser?.key]);

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
        mt={2}
      >
        <Grid>
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} size="small" />
            )}
            value={selectedDate1}
            onChange={(e) => {
              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} size="small" />
            )}
            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 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
        </Grid>
        <Tooltip title="خروجی اکسل">
          <a
            href={`${
              axios.defaults.baseURL
            }kill_house_free_sale_bar_information_for_excel_excel/?key=${userKey}&role=${getRoleFromUrl()}${
              checkPathStartsWith("slaughter")
                ? `&role_key=${selectedSubUser?.key}`
                : ""
            }&date1=${selectedDate1}&date2=${selectedDate2}`}
            rel="noreferrer"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>
      </Grid>

      <Grid container xs={12} mt={2} mb={4} isDashboard>
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            "تعداد فروش",
            "خریدار",
            "حجم لاشه ها (تقریبی)",
            "وزن کل لاشه ها",
          ]}
          data={[
            [
              dashboardData?.numberOfAllocations?.toLocaleString(),
              dashboardData?.numberOfBuyers?.toLocaleString(),
              dashboardData?.totalNumberOfAllocationCarcasses?.toLocaleString(),
              dashboardData?.totalWeightOfAllocationCarcasses?.toLocaleString(),
            ],
          ]}
          title={"خلاصه اطلاعات"}
        />
      </Grid>

      <Grid container xs={12}>
        <Button
          variant="contained"
          onClick={() => {
            dispatch(
              DRAWER({
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                size: {
                  xs: "100%",
                  sm: "350px",
                },
                content: (
                  <SlaughterSellCarcassOutProvinceSellSubmitSell
                    updateTable={updateTable}
                  />
                ),
                title: "ثبت اطلاعات فروش",
              })
            );
          }}
        >
          ثبت اطلاعات فروش
        </Button>
      </Grid>

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