import { Tooltip } from "@mui/material";
import { Button, TextField } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import axios from "axios";
import moment from "moment/moment";
import { useContext, useEffect, useState } from "react";
import { RiFileExcel2Fill } from "react-icons/ri";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { formatJustDate } from "../../../../utils/formatTime";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { RiSearchLine } from "react-icons/ri";
import { slaughterGetFreeBuyRequests } from "../../services/slaughter-get-free-buy-requests";

export const SlaughterFreeBuyArchive = () => {
  const userKey = useSelector((state) => state.userSlice.userProfile.key);
  const dispatch = useDispatch();
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);
  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 handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const fetchApiData = async (page) => {
    try {
      const response = await dispatch(
        slaughterGetFreeBuyRequests({
          date1: selectedDate1,
          date2: selectedDate2,
          value: textValue || "",
          type: "archive",
          page: page,
          page_size: perPage,
        })
      );
      if (response.payload?.data) {
        setData(response.payload.data.results);
        setTotalRows(response.payload.data.count);
      }
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const handlePageChange = (page) => {
    fetchApiData(page, textValue);
  };

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    try {
      const response = await dispatch(
        slaughterGetFreeBuyRequests({
          date1: selectedDate1,
          date2: selectedDate2,
          value: textValue || "",
          type: "archive",
        })
      );
      if (response.payload?.data) {
        setData(response.payload.data.results);
        setTotalRows(response.payload.data.count);
      }
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const getItemState = (item) => {
    let state = "";
    if (item.directBuyingState === "pending") {
      state = "در انتظار تایید";
    } else if (item.directBuyingState === "rejected") {
      state = "رد شده";
    } else if (item.directBuyingState === "accepted") {
      state = "تایید شده";
    } else if (item.directBuyingState === "deleted") {
      state = "حذف شده";
    }
    return state;
  };

  useEffect(() => {
    fetchApiData(1);
  }, [selectedDate1, selectedDate2, perPage, textValue, dispatch]);

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        formatJustDate(item?.createDate),
        formatJustDate(item.reciveDate),
        `${item.killHouse.name} (${item.killHouse.killHouseOperator.user.mobile})`,
        item?.slaughterHouse
          ? item?.slaughterHouse?.name
          : item?.killHouse?.name,
        `${item?.poultry?.userprofile?.fullName} (${item?.poultry?.userprofile?.mobile})`,
        `${item.chickenBreed ? item.chickenBreed : "-"}`,
        item.killCapacity,
        item.IndexWeight,
        (item.IndexWeight * item.killCapacity)?.toLocaleString(),
        item?.inputDirectBuyingCode,
        getItemState(item),
      ];
    });

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

  return (
    <Grid container direction="column" gap={SPACING.SMALL} alignItems="start">
      <Grid container alignItems="center" gap={SPACING.SMALL} p="5px">
        <form onSubmit={handleSubmit}>
          <Grid container alignItems="center" gap={SPACING.SMALL}>
            <TextField
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
            <Grid container gap={2}>
              <DatePicker
                label="از تاریخ"
                id="date"
                renderInput={(params) => (
                  <TextField style={{ width: "160px" }} {...params} />
                )}
                value={selectedDate1}
                onChange={(e) => {
                  setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                }}
              />
              <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="خروجی اکسل">
              <a
                href={`${
                  axios.defaults.baseURL
                }direct_purchase_archive_excel/?date1=${selectedDate1}&date2=${selectedDate2}&role=${getRoleFromUrl()}&key=${userKey}`}
                rel="noreferrer"
              >
                <Button color="success">
                  <RiFileExcel2Fill size={32} />
                </Button>
              </a>
            </Tooltip>
          </Grid>
        </form>
      </Grid>
      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "تاریخ ثبت درخواست",
          "تاریخ کشتار",
          "خریدار",
          "محل کشتار",
          "مرغدار (تلفن)",
          "نژاد",
          "تعداد درخواست (قطعه)",
          "میانگین وزنی (کیلوگرم)",
          "وزن کل (کیلوگرم)",
          "کداحراز",
          "وضعیت",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="بایگانی خرید مستقیم"
      />
    </Grid>
  );
};
