import { Button, TextField, Tooltip } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import axios from "axios";
import moment from "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 { provinceGetDeletedAllocatedRequestsService } from "../../services/province-get-deleted-allocated-requests";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { provinceGetDashboardDeletedKillRequestService } from "../../services/get-dahsnoard-province-kill-request";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { RiSearchLine } from "react-icons/ri";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const ProvinceGetDeletedAllocatedRequests = () => {
  const dispatch = useDispatch();
  const [dataTable, setDataTable] = useState();
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

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

  const [textValue, setTextValue] = useState("");

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

  const { provinceGetDeletedAllocatedRequests } = useSelector(
    (state) => state.provinceSlice
  );

  useEffect(() => {
    dispatch(
      provinceGetDeletedAllocatedRequestsService({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
        selectedDate1,
        selectedDate2,
        textValue,
      })
    );
  }, [selectedDate1, selectedDate2, selectedSubUser?.key]);

  const handleSubmit = () => {
    dispatch(
      provinceGetDeletedAllocatedRequestsService({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
        selectedDate1,
        selectedDate2,
        textValue,
      })
    );

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

  useEffect(() => {
    const d = provinceGetDeletedAllocatedRequests?.map((item, i) => {
      let state = "";
      if (item.allocatedState === "pending") {
        state = "در انتظار تایید";
      } else if (item.allocatedState === "accepted") {
        state = "تایید شده";
      } else if (item.allocatedState === "rejected") {
        state = "رد شده";
      }
      return [
        i + 1,
        item?.orderCode,
        item?.freezing ? "انجماد" : item?.export ? "صادرات" : "عادی",
        item?.poultryUnitName,
        `${item?.poultryFullName} (${item?.poultryMobile})`,
        item?.poultryCity,
        formatJustDate(item?.sendDate),
        item.poultryQuantity,
        formatJustDate(item?.dateOfAllocate),
        item?.killHouseName,
        item?.killHouseCity,
        item?.amount?.toLocaleString() + " ﷼",
        item?.killHousePrice?.toLocaleString() + " ﷼",
        item?.allocatedQuantity,
        state,
        item?.allocatedCarState ? "دارد" : "ندارد",
        item?.allocatedRemainQuantity,
      ];
    });
    setDataTable(d);
  }, [provinceGetDeletedAllocatedRequests]);

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

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

  return (
    <Grid>
      <Grid
        container
        justifyContent="center"
        alignItems="center"
        mb={SPACING.MEDIUM}
        mt={SPACING.SMALL}
      >
        <Grid container alignItems="center" gap={SPACING.SMALL}>
          <Grid style={{ width: 160 }}>
            <DatePicker
              label="از تاریخ"
              renderInput={(params) => <TextField {...params} />}
              value={selectedDate1}
              onChange={(e) => {
                setSelectedDate1(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid style={{ width: 160 }}>
            <DatePicker
              label="تا تاریخ"
              renderInput={(params) => <TextField {...params} />}
              value={selectedDate2}
              onChange={(e) => {
                setSelectedDate2(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>

          <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>

          <Tooltip title="خروجی اکسل">
            <a
              href={`${
                axios.defaults.baseURL
              }allocated_excel/?start=${selectedDate1}&end=${selectedDate2}&type=deleted&role=${getRoleFromUrl()}${
                checkPathStartsWith("province")
                  ? `&role_key=${selectedSubUser?.key}`
                  : ""
              }&key=${userKey}&filter=search&value=${textValue}`}
              rel="noreferrer"
            >
              <Button color="success">
                <RiFileExcel2Fill size={32} />
              </Button>
            </a>
          </Tooltip>
        </Grid>

        <Grid container mt={2} mb={4} isDashboard xs={12}>
          <ResponsiveTable
            noPagination
            isDashboard
            columns={[
              "تعداد تخصیصات",
              "حجم تخصیصات",
              "وزن تخصیصات",
              "تعداد تخصیصات تایید شده",
              "حجم تخصیصات تایید شده",
              "تعداد تخصیصات در انتظار تایید",
              "حجم تخصیصات در انتظار تایید",
              "تعداد تخصیصات رد شده",
              "حجم تخصیصات رد شده",
              "تعداد تخصیصات دارای ماشین",
              "حجم تخصیصات دارای ماشین",
              "وزن تخصیصات دارای ماشین",
              "تعداد بارها",
              "حجم بارها",
              "وزن بارها",
              "تعداد تخصیصات فاقد ماشین",
              "حجم تخصیصات فاقد ماشین",
              "وزن تخصیصات فاقد ماشین",
            ]}
            data={[
              [
                dashboardData?.lenProvinceRequest?.toLocaleString(),
                dashboardData?.quantity?.toLocaleString(),
                dashboardData?.weight?.toLocaleString(),
                dashboardData?.acceptedProvinceKillRequests?.toLocaleString(),
                dashboardData?.acceptedProvinceKillRequestsQuantity?.toLocaleString(),
                dashboardData?.pendingProvinceKillRequests?.toLocaleString(),
                dashboardData?.pendingProvinceKillRequestsQuantity?.toLocaleString(),
                dashboardData?.rejectedProvinceKillRequests?.toLocaleString(),
                dashboardData?.rejectedProvinceKillRequestsQuantity?.toLocaleString(),
                dashboardData?.lenHasCar?.toLocaleString(),
                dashboardData?.hasCarQuantity?.toLocaleString(),
                dashboardData?.hasCarWeight?.toLocaleString(),
                dashboardData?.lenKillRequests?.toLocaleString(),
                dashboardData?.realQuantity?.toLocaleString(),
                dashboardData?.realWeight?.toLocaleString(),
                dashboardData?.lenHasntCar?.toLocaleString(),
                dashboardData?.hasntCarQuantity?.toLocaleString(),
                dashboardData?.hasntCarWeight?.toLocaleString(),
              ],
            ]}
            title={"خلاصه اطلاعات"}
          />
        </Grid>
        <ResponsiveTable
          paginated
          title="تخصیص های حذف شده"
          columns={[
            "ردیف",
            "کدسفارش",
            "نوع کشتار",
            "نام فارم",
            "نام مرغدار",
            "شهر",
            "تاریخ کشتار",
            "تعداد کشتار",
            "تاریخ تخصیص",
            "خریدار",
            "شهر خریدار",
            "قیمت مرغدار",
            "قیمت کشتارگاه",
            "تعداد تخصیص",
            "وضعیت تایید خریدار",
            "وضعیت تخصیص ماشین",
            "مانده قابل تخصیص",
          ]}
          data={dataTable}
        />
      </Grid>
    </Grid>
  );
};
