import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import moment from "moment";
import axios from "axios";
import { Button, TextField } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import { RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import { CheckCleanceCode } from "../../../../components/check-clearance-code/ChechClearanceCode";
import { stewardSellOutGetDashboard } from "../../../guild/services/steward-sell-out-get-dashboard";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { StewardSellOutOfProvinceSubmitSell } from "../steward-purchase-out-province-submit-sell/StewardSellOutOfProvinceSubmitSell";
import { StewardOutProvinceRegistrationCodeInput } from "../steward-out-province-registration-code-input/StewardOutProvinceRegistrationCodeInput";
import { StewardOutProvinceSalesOperations } from "../steward-out-province-sales-operations/StewardOutProvinceSalesOperations";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const StewardSellOutOfProvinceSells = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const dispatch = useDispatch();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  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 [dashboardData, setDashboardData] = useState([]);

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

  const getDashboardData = () => {
    dispatch(
      stewardSellOutGetDashboard({
        selectedDate1,
        selectedDate2,
        role_key: checkPathStartsWith("steward") ? selectedSubUser?.key : "",
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

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

  useEffect(() => {
    if (selectedDate1 && selectedDate2) {
      fetchApiData(1);
      setPage(1);
      getDashboardData();
    }
  }, [selectedDate1, selectedDate2, perPage]);

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

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

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

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

  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?.systemRegistrationCode ? (
          item?.loggedRegistrationCode ? (
            "تایید شده"
          ) : item?.registrationCode ? (
            <StewardOutProvinceRegistrationCodeInput
              key={i}
              item={item}
              fetchApiData={() => fetchApiData(page)}
            />
          ) : (
            "-"
          )
        ) : (
          "-"
        ),
        <StewardOutProvinceSalesOperations
          key={i}
          item={item}
          updateTable={updateTable}
          fetchApiData={fetchApiData}
          page={page}
        />,
      ];
    });

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

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

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

  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()}&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?.numberOfBars?.toLocaleString(),
              dashboardData?.numberOfBuyers?.toLocaleString(),
              dashboardData?.barsQuantity?.toLocaleString(),
              dashboardData?.barsWeight?.toLocaleString(),
            ],
          ]}
          title={"خلاصه اطلاعات"}
        />
      </Grid>

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

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