import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import axios from "axios";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Button, TextField, Tooltip } from "@mui/material";
import { VetFarmEditTrafficCode } from "../../../vet-farm/components/vet-farm-edit-traffic-code/VetFarmEditTrafficCode";
import { format } from "date-fns-jalali";
import { SlaughterNoneRecieptOperation } from "../slaughter-none-reciept-operation/SlaughterNoneRecieptOperation";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import moment from "moment";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { AppContext } from "../../../../contexts/AppContext";
import { DatePicker } from "@mui/x-date-pickers";
import ShowImage from "../../../../components/show-image/ShowImage";
import { formatJustDate } from "../../../../utils/formatTime";

export const SlaughterEnterNoneReciept = () => {
  const userKey = useSelector((state) => state.userSlice.userProfile.key);
  const [openNotif] = useContext(AppContext);

  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 dispatch = useDispatch();

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

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

  const fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `non-receipt-request/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}`
    );
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);

    dispatch(LOADING_END());
  };

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

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

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

  useEffect(() => {
    fetchApiData(1);
  }, []);

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

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

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

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

  // useEffect(() => {
  //   dispatch(
  //     slaughterEnterLoadInformationGetDashboard({
  //       selectedDate1,
  //       selectedDate2,
  //       text: textValue,
  //     })
  //   ).then((r) => {
  //     setDashboardData(r.payload.data);
  //   });
  // }, [selectedDate1, selectedDate2]);

  // const information = () => {
  //   if (getRoleFromUrl() !== "KillHouse") {
  //     return ["عملیات"];
  //   } else {
  //     return [];
  //   }
  // };
  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        <ShowImage key={i} src={item?.assignmentInfo?.imageWithoutBar} />,
        <ShowImage key={i} src={item?.assignmentInfo?.imageWithBar} />,
        item?.barCode,
        <VetFarmEditTrafficCode
          key={i}
          updateTable={fetchApiData}
          killHouseRequestKey={item.key}
          trafficCode={item?.trafficCode}
          isEditable={
            getRoleFromUrl() === "ProvinceOperator" ||
            getRoleFromUrl() === "SuperAdmin" ||
            getRoleFromUrl() === "AdminX" ||
            getRoleFromUrl() === "Supporter" ||
            getRoleFromUrl() === "VetSupervisor" ||
            (item.trash !== true &&
              item.assignmentStateArchive === "pending" &&
              !item?.clearanceCode &&
              (getRoleFromUrl() === "VetFarm" ||
                getRoleFromUrl() === "CityVet"))
          }
        />,
        item?.amount?.toLocaleString() + " ﷼",
        item?.poultryRequest.sendDate
          ? format(new Date(item?.poultryRequest.sendDate), "yyyy/MM/dd")
          : "-",
        `${item.killhouseUser?.name} (${item.killhouseUser?.killHouseOperator?.user?.mobile})`,
        item?.killer
          ? `${item?.killer?.name} (${item?.killer?.killHouseOperator?.user?.mobile})`
          : "-",
        `${item.poultryRequest?.poultry?.unitName} (${item.poultryRequest.poultry?.user?.mobile})`,
        item?.poultryRequest?.age,
        item.quantity?.toLocaleString(),
        item?.weightInfo?.weight?.toLocaleString(),
        item?.poultryRequest?.amount?.toLocaleString() + " ﷼",
        item?.weightInfo?.killHousePrice?.toLocaleString() + " ﷼",
        `${item.addCar.driver.typeCar} ${item.addCar.driver.pelak}`,
        `${item.addCar.driver.driverName} (${item.addCar.driver.driverMobile})`,
        item.vetAcceptedRealQuantity?.toLocaleString(),
        item.vetAcceptedRealWeight?.toLocaleString(),
        item?.poultryRequest.orderCode,
        item?.poultryRequest?.freezing
          ? "انجماد"
          : item?.poultryRequest?.export
          ? "صادرات"
          : "عادی",
        item?.poultryRequest?.freeSaleInProvince ? "آزاد" : "دولتی",
        item?.nonReceiptState === "accepted"
          ? "تایید شده"
          : item?.nonReceiptState === "rejected"
          ? "رد شده"
          : "درانتظار تایید",
        item?.nonReceiptMessage,
        formatJustDate(item?.nonReceiptCheckDate) || "-",
        item?.nonReceiptChecker && item?.nonReceiptCheckerMobile
          ? `${item.nonReceiptChecker}(${item.nonReceiptCheckerMobile})`
          : "-",
        item?.message,
        <SlaughterNoneRecieptOperation
          key={i}
          item={item}
          updateTable={updateTable}
        />,
      ];
    });

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

  return (
    <Grid container justifyContent="center">
      <Grid
        container
        alignItems="start"
        justifyContent="space-between"
        gap={2}
        paddingTop={2}
        mb={1}
      >
        <Grid container alignItems="center" gap={SPACING.SMALL}>
          <Grid>
            <DatePicker
              label="از تاریخ"
              renderInput={(params) => (
                <TextField
                  {...params}
                  style={{ width: "160px" }}
                  size="small"
                />
              )}
              value={selectedDate1}
              onChange={(newValue) => {
                setSelectedDate1(moment(newValue).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid>
            <DatePicker
              label="تا تاریخ"
              renderInput={(params) => (
                <TextField
                  {...params}
                  style={{ width: "160px" }}
                  size="small"
                />
              )}
              value={selectedDate2}
              onChange={(newValue) => {
                setSelectedDate2(moment(newValue).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
          <Tooltip title="خروجی اکسل">
            <Button
              color="success"
              onClick={() => {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                  severity: "success",
                });
                const link = `${
                  axios.defaults.baseURL
                }non_receipt_request_excel/?role=${getRoleFromUrl()}&key=${userKey}&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}`;
                window.location.href = link;
              }}
            >
              <RiFileExcel2Fill size={32} />
            </Button>
          </Tooltip>
        </Grid>
      </Grid>
      {/* <Grid container mt={2} mb={4} isDashboard>
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            "تعداد بار",
            "مجموع تعداد اولیه",
            "مجموع وزن اولیه (کیلوگرم)",
            "مجموع تعداد تحویلی دامپزشک",
            "مجموع وزن تحویلی دامپزشک (کیلوگرم)",
          ]}
          data={[
            [
              dashboardData?.lenKillHouseRequest?.toLocaleString(),
              dashboardData?.firstQuantity?.toLocaleString(),
              dashboardData?.firstWeight?.toLocaleString(),
              dashboardData?.vetAcceptedRealQuantity?.toLocaleString(),
              dashboardData?.vetAcceptedRealWeight?.toLocaleString(),
            ],
          ]}
          title={"خلاصه اطلاعات"}
        />
      </Grid> */}

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