import { Button, IconButton, TextField, Tooltip } from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import DeleteIcon from "@mui/icons-material/Delete";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { getSlaughtersKillRequestService } from "../../../city/services/get-slaughters-kill-request";
import { slaughterDeleteRequest } from "../../../slaughter-house/services/slaughter-delete-request";
import { InspectorKillHouseNewRequest } from "../../../inspector/components/inspector-killhouse-new-request/inspector-killhouse-new-request";
import { SPACING } from "../../../../data/spacing";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment/moment";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import axios from "axios";
import { RiFileExcel2Fill } from "react-icons/ri";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { provinceManageSlaughterRequestDashboard } from "../../services/province-manage-slaughter-request-dashboard";

export const ProvinceManageSlaughterRequest = () => {
  const dispatch = useDispatch();
  const [
    openNotif,
    ,
    selectedDate1,
    setSelectedDate1,
    selectedDate2,
    setSelectedDate2,
  ] = useContext(AppContext);

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

  const { getSlaughtersKillRequest } = useSelector((state) => state.citySlice);

  const [dataTableSlaughterRequests, setDataTableSlaughterRequests] = useState(
    []
  );

  // useEffect(() => {
  //   dispatch(poultryGetAutoRequestService()).then((r) =>
  //     setAutoPoultryRequestChecked(r.payload.data[0]?.active)
  //   );
  // }, []);

  // const [autoPoultryRequestChecked, setAutoPoultryRequestChecked] =
  //   useState(false);

  // const handleChangeAutoPoultryRequestChecked = (event) => {
  //   setAutoPoultryRequestChecked(event.target.checked);
  //   dispatch(poultryAutoRequestService({ active: event.target.checked }));
  // };

  useEffect(() => {
    dispatch(getSlaughtersKillRequestService({ selectedDate1, selectedDate2 }));
  }, [selectedDate1, selectedDate2]);

  useEffect(() => {
    const e = getSlaughtersKillRequest?.map((item, i) => {
      return [
        i + 1,
        item?.killHouse?.killer ? "کشتارکن" : "کشتارگاه",
        `${item?.killHouse?.name} (${item.killHouse.killHouseOperator.user.mobile})`,
        item?.slaughterHouse?.name
          ? item?.slaughterHouse?.name
          : "مکان کشتارگاه",
        item?.killHouseVet
          ? `${item?.killHouseVet?.vet?.user?.fullname} (${item?.killHouseVet?.vet?.user?.mobile})`
          : "-",
        formatTime(item?.createDate),
        formatJustDate(item?.reciveDate),
        item?.reciveTime,
        item?.killCapacity?.toLocaleString(),
        item?.remainQuantity?.toLocaleString(),
        (item?.killCapacity - item?.remainQuantity).toLocaleString(),

        <IconButton
          key={i}
          aria-label="delete"
          color="error"
          onClick={() => {
            dispatch(LOADING_START());
            dispatch(
              slaughterDeleteRequest({
                id: item.id,
              })
            ).then((r) => {
              dispatch(LOADING_END());
              if (r.error) {
                if (r.error.message.includes("403")) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "این درخواست از سمت استان پذیرفته شده و قابل حذف نمی باشد!",
                    severity: "error",
                  });
                } else {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "مشکلی پیش آمده است!",
                    severity: "error",
                  });
                }
              } else {
                dispatch(
                  getSlaughtersKillRequestService({
                    selectedDate1,
                    selectedDate2,
                  })
                );

                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          }}
        >
          <DeleteIcon />
        </IconButton>,
      ];
    });
    setDataTableSlaughterRequests(e);
  }, [getSlaughtersKillRequest]);

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

  useEffect(() => {
    dispatch(
      provinceManageSlaughterRequestDashboard({
        selectedDate1,
        selectedDate2,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  }, [selectedDate1, selectedDate2]);

  return (
    <Grid container width="100%">
      <Grid container justifyContent="space-between" mb={SPACING.MEDIUM}>
        {(getRoleFromUrl() === "ProvinceOperator" ||
          getRoleFromUrl() === "SuperAdmin") && (
          <Grid>
            <Button
              className="new-request-form-button"
              variant={"contained"}
              onClick={() => {
                dispatch(
                  DRAWER({
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    content: <InspectorKillHouseNewRequest />,
                    title: "ثبت درخواست کشتار",
                  })
                );
              }}
            >
              ثبت درخواست کشتار جدید
            </Button>
          </Grid>
        )}

        {/* {getRoleFromUrl() === "ProvinceOperator" && (
          <Grid>
            <FormControlLabel
              control={
                <Switch
                  checked={autoPoultryRequestChecked}
                  onChange={handleChangeAutoPoultryRequestChecked}
                />
              }
              label="ارسال درخواست کشتار ها بصورت خودکار"
              labelPlacement="start"
            />
          </Grid>
        )} */}
      </Grid>
      <Grid container alignItems="center" gap={1} xs={12}>
        <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}kill_house_excel/?start=${selectedDate1}&end=${selectedDate2}`}
            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?.lenKillRequest?.toLocaleString(),
              dashboardData?.quantity?.toLocaleString(),
              dashboardData?.remainQuantity?.toLocaleString(),
              dashboardData?.leftOver?.toLocaleString(),
            ],
          ]}
          title={"خلاصه اطلاعات"}
        />
      </Grid>

      <ResponsiveTable
        paginated
        title={"اعلام نیاز خریداران و کشتارگاه ها"}
        columns={[
          "ردیف",
          "ماهیت",
          "خریدار",
          "محل کشتار",
          "دامپزشک کشتارگاه",
          "تاریخ ایجاد درخواست",
          "تاریخ کشتار",
          "زمان دریافت",
          "تعداد درخواست (قطعه)",
          "مانده (قطعه)",
          "تعداد تخصیص داده شده (قطعه)",
          "حذف",
        ]}
        data={dataTableSlaughterRequests}
      />
    </Grid>
  );
};
