import { Button, TextField, Tooltip, Typography } from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useLocation } from "react-router-dom";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { CityNewKillRequest } from "../../../city/components/city-new-kill-request/CityNewKillRequest";
import { AppContext } from "../../../../contexts/AppContext";
import { hourLimitKillRequestService } from "../../../city/services/hour-limit-kill-request";
import { hourLimitGetKillRequestService } from "../../../city/services/hour-limit-get-kill-request";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { getPoultryRequestsTotalQuantityService } from "../../../city/services/get-poultry-requests-total-quantity";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { ProvinceManagePoultryRequestOperations } from "../province-manage-poultry-request-operations/ProvinceManagePoultryRequestOperations";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { deleteDebtorKillhouses } from "../../services/delete-debtor-killhouses";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";

export const ProvinceManagePoultryRequest = () => {
  const authToken = useSelector((state) => state.userSlice.authToken);
  const { poultryRequestsTotalQuantity } = useSelector(
    (state) => state.citySlice
  );
  const { pathname } = useLocation();
  const dispatch = useDispatch();
  const [isChecked, setIsChecked] = useState(false);
  const [selectedHour, setSelectedHour] = useState("");

  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 handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

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

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

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

    try {
      const response = await axios.get(
        `Poultry_Request/?role=${getRoleFromUrl()}&today&date1=${selectedDate1}&date2=${selectedDate2}&search=filter&value=${
          textValue || ""
        }`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const [selectedDate, setSelectedDate] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );

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

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

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

  useEffect(() => {
    dispatch(getPoultryRequestsTotalQuantityService(selectedDate));
  }, [selectedDate]);

  useEffect(() => {
    dispatch(hourLimitGetKillRequestService()).then((r) => {
      setIsChecked(r.payload.data?.[0]?.active);
      setSelectedHour(r.payload.data?.[0]?.hour);
    });
    dispatch(deleteDebtorKillhouses());
  }, []);

  useEffect(() => {
    if (isChecked && selectedHour) {
      dispatch(
        hourLimitKillRequestService({ hour: selectedHour, active: isChecked })
      );
    }
    if (!isChecked && selectedHour) {
      setSelectedHour(null);
      dispatch(hourLimitKillRequestService({ hour: 0, active: isChecked }));
    }
  }, [selectedHour, isChecked]);

  const urlRole = window.location.pathname.split("/")[1];
  const fileUrl = "/" + urlRole + "/file/";

  const getItemSellState = (item) => {
    let sellType = "";
    if (item?.market) {
      sellType = "پنل معاملات";
    } else if (item?.directBuying) {
      sellType = "خرید مستقیم";
    } else if (item?.union) {
      sellType = "خرید خارج از استان";
    } else {
      sellType = "اتحادیه";
    }
    return sellType;
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        <ProvinceManagePoultryRequestOperations
          fileUrl={fileUrl}
          item={item}
          updateTable={updateTable}
          key={i}
        />,
        item.orderCode,
        getItemFreeSaleInProvince(item),
        item?.freezing ? "انجماد" : item?.export ? "صادرات" : "عادی",
        getItemSellState(item),
        formatTime(item?.createDate) +
          " " +
          `(${item?.registrar?.fullname} - ${getFaUserRole(
            item?.registrar?.role
          )})`,
        formatJustDate(item?.sendDate),
        `${item?.poultry?.unitName} (${item?.poultry?.user?.mobile})`,
        item?.killHouseList?.length ? item?.killHouseList.join(" - ") : "ندارد",
        `${item?.poultry?.address?.city?.name}/${
          item?.poultry?.cityOperator
            ? item?.poultry?.cityOperator
            : "بدون تعاونی"
        }`,
        item?.killingAge,
        item?.IndexWeight,
        item?.hatching?.totalWeight?.toLocaleString(),
        item?.firstQuantity.toLocaleString(),
        item?.amount.toLocaleString() + " ﷼",
        item?.hatching?.leftOver?.toLocaleString(),
        item.quantity?.toLocaleString(),
        (item.quantity - item?.remainQuantity).toLocaleString(),
        item?.remainQuantity?.toLocaleString(),
        <Typography
          key={i}
          variant="body2"
          sx={{
            color:
              item.hatching.fileState === "confirmation_code_pending"
                ? "red"
                : "black",
          }}
        >
          {item.hatching.fileState === "province_state_pending"
            ? "در انتظار تایید"
            : item.hatching.fileState === "allocated_pending"
            ? "آماده تخصیص"
            : item.hatching.fileState === "confirmation_code_pending"
            ? "در انتظار ورود کد احراز"
            : "تخصیص داده شده"}
        </Typography>,
      ];
    });

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

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

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

  const tableTitle = (
    <Grid
      container
      alignItems="center"
      mb={SPACING.SMALL}
      gap={SPACING.SMALL}
      justifyContent="center"
    >
      <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>
            <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="خروجی اکسل">
            {/* <a
              href={`${
                axios.defaults.baseURL
              }poultry_kill_request_excel/?start=${selectedDate1}&end=${selectedDate2}&role=${getRoleFromUrl()}&token=${authToken}`}
              rel="noreferrer"
            > */}
            <Button
              color="success"
              onClick={() => {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                  severity: "success",
                });
                const link = `${
                  axios.defaults.baseURL
                }poultry_kill_request_excel/?start=${selectedDate1}&end=${selectedDate2}&role=${getRoleFromUrl()}&token=${authToken}`;
                window.location.href = link;
              }}
            >
              <RiFileExcel2Fill size={32} />
            </Button>
            {/* </a> */}
          </Tooltip>
        </Grid>
      </form>
    </Grid>
  );

  const getItemFreeSaleInProvince = (item) => {
    let sellType = "";
    if (item?.freeSaleInProvince) {
      sellType = "آزاد";
    } else {
      sellType = "دولتی";
    }
    return sellType;
  };

  return (
    <Grid container>
      <Grid
        container
        alignItems="center"
        justifyContent="space-between"
        gap={4}
        xs={12}
      >
        <Grid>
          {pathname !== "/vet-supervisor/hatching" && (
            <Button
              className="avicultureNewRequestBtn"
              variant={"contained"}
              onClick={() => {
                dispatch(
                  DRAWER({
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    title: "ثبت درخواست کشتار جدید",
                    content: <CityNewKillRequest updateTable={updateTable} />,
                  })
                );
              }}
            >
              ثبت درخواست کشتار جدید
            </Button>
          )}
        </Grid>
        <Grid container>
          <Grid my={SPACING.SMALL}>
            <Grid mb={2} container alignItems="center" gap={SPACING.SMALL}>
              <Grid>
                <Typography>اطلاعات کشتار</Typography>
              </Grid>
              <Grid>
                <DatePicker
                  label="تاریخ"
                  id="date"
                  renderInput={(params) => (
                    <TextField style={{ width: "160px" }} {...params} />
                  )}
                  value={selectedDate}
                  onChange={(e) => {
                    setSelectedDate(moment(e).format("YYYY-MM-DD"));
                  }}
                />
              </Grid>
            </Grid>
          </Grid>
          <Grid xs={12} mb={2} isDashboard>
            <ResponsiveTable
              isDashboard
              noPagination
              title={"خلاصه اطلاعات"}
              columns={[
                "درخواست های کشتار صادر شده",
                "درخواست های کشتار تایید شده",
                "درخواست های رد شده",
                "درخواست خریداران",
                "درخواست های خرید مستقیم",
                "مانده در سالن (جوجه ریزی 45 تا 65 روز)",
              ]}
              data={[
                [
                  poultryRequestsTotalQuantity?.firstQuantity
                    ? poultryRequestsTotalQuantity?.firstQuantity?.toLocaleString() +
                      " قطعه"
                    : 0,
                  poultryRequestsTotalQuantity?.acceptedQuantity
                    ? poultryRequestsTotalQuantity?.acceptedQuantity?.toLocaleString() +
                      " قطعه"
                    : 0,
                  poultryRequestsTotalQuantity?.rejectedQuantity
                    ? poultryRequestsTotalQuantity?.rejectedQuantity?.toLocaleString() +
                      " قطعه"
                    : 0,
                  poultryRequestsTotalQuantity?.killRequestsQuantity
                    ? poultryRequestsTotalQuantity?.killRequestsQuantity?.toLocaleString() +
                      " قطعه"
                    : 0,
                  poultryRequestsTotalQuantity?.directBuyingQuantity
                    ? poultryRequestsTotalQuantity?.directBuyingQuantity?.toLocaleString() +
                      " قطعه"
                    : 0,
                  poultryRequestsTotalQuantity?.ageUp45
                    ? poultryRequestsTotalQuantity?.ageUp45?.toLocaleString() +
                      " قطعه"
                    : 0,
                ],
              ]}
            />
          </Grid>
          <Grid mt={2}>
            {tableTitle}
            <ResponsiveTable
              data={tableData}
              columns={[
                "ردیف",
                "عملیات",
                "کدسفارش",
                "فروش",
                "کشتار",
                "درخواست",
                "تاریخ ثبت درخواست",
                "تاریخ کشتار",
                "مرغدار",
                "کشتارگاه های پیشنهادی",
                "شهر/تعاونی",
                "سن مرغ",
                "میانگین وزنی",
                "وزن تقریبی",
                "حجم درخواست کشتار",
                "قیمت مرغدار",
                "مانده در سالن",
                "تایید شده",
                "تخصیص داده شده",
                "مانده قابل تخصیص",
                "وضعیت",
              ]}
              handlePageChange={handlePageChange}
              totalRows={totalRows}
              page={page}
              perPage={perPage}
              handlePerRowsChange={handlePerRowsChange}
              title="اطلاعات کشتار"
            />
          </Grid>
        </Grid>
      </Grid>
    </Grid>
  );
};
