import { Button, IconButton, Tooltip } from "@mui/material";
import { SPACING } from "../../../../data/spacing";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useFormik } from "formik";
import moment from "moment";
import { useState } from "react";
import DeleteIcon from "@mui/icons-material/Delete";
import { useContext } from "react";
import Tour from "reactour";
import { AvicultureNewHatching } from "../../../aviculture/components/aviculture-new-hatching/AvicultureNewHatching";
import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { avicultureGetHatchings } from "../../../aviculture/services/aviculture-get-hatchings";
import { Yup } from "../../../../lib/yup/yup";
import { avicultureDeleteHatching } from "../../../aviculture/services/aviculture-delete-hatching";
import { formatJustDate } from "../../../../utils/formatTime";

const steps = [
  {
    selector: ".first-step",
    content: () => <div>برای ثبت جوجه ریزی اینجا کلیک کنید!</div>,
  },
  {
    selector: ".second",
    content: () => (
      <div>در این قسمت جوجه ریزی های ثبت شده توسط شما نمایش داده می شود.</div>
    ),
  },
];

export const AdminHatching = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const { avicultureHatchings } = useSelector((state) => state.avicultureSlice);
  const [isTourOpen, setIsTourOpen] = useState(false);
  const [dataTable, setDataTable] = useState([]);
  const [dataTableArchived, setDataTableArchuved] = useState([]);

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

  useEffect(() => {
    const filteredData = avicultureHatchings?.filter(
      (item) => item.allowHatching === "pending"
    );

    const filteredDataArchived = avicultureHatchings?.filter(
      (item) => item.allowHatching === "True"
    );

    const d = filteredData?.map((item, i) => {
      const quantity = item?.quantity || 0;
      const losses = item?.losses || 0;
      const leftOver = item?.leftOver || 0;
      const killedNumber = quantity - losses - leftOver;
      const percentage =
        quantity > 0
          ? (value) => ((value * 100) / quantity).toFixed(0)
          : () => "0";

      return [
        i + 1,
        item?.poultry?.unitName || "",
        item?.hall || "",
        item?.period || "",
        formatJustDate(item?.createDate),
        formatJustDate(item?.date),
        item?.chickenBreed || "",
        item?.age || "",
        quantity,
        `${losses} (%${percentage(losses)})`,
        killedNumber + ` (%${percentage(killedNumber)})`,
        `${leftOver} (%${percentage(leftOver)})`,
        <Tooltip key={item?.key} title={"حذف جوجه ریزی"} placement="left-start">
          <IconButton
            aria-label="delete"
            color="error"
            onClick={() => {
              dispatch(LOADING_START());
              dispatch(avicultureDeleteHatching(item?.key)).then((r) => {
                dispatch(LOADING_END());
                if (r?.error) {
                  const errorMessage = r.error?.message || "";
                  if (errorMessage.includes("403")) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "برای این جوجه ریزی درخواست کشتار ثبت شده است!",
                      severity: "error",
                    });
                  } else if (errorMessage.includes("400")) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "برای این جوجه ریزی بازرسی ثبت شده است!",
                      severity: "error",
                    });
                  } else {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "مشکلی پیش آمده است!",
                      severity: "error",
                    });
                  }
                } else {
                  dispatch(avicultureGetHatchings());
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "عملیات با موفقیت انجام شد.",
                    severity: "success",
                  });
                }
              });
            }}
          >
            <DeleteIcon />
          </IconButton>
        </Tooltip>,
      ];
    });

    setDataTable(d);

    const b = filteredDataArchived?.map((item, i) => {
      const quantity = item?.quantity || 0;
      const losses = item?.losses || 0;
      const leftOver = item?.leftOver || 0;
      const killedNumber = quantity - losses - leftOver;
      const percentage =
        quantity > 0
          ? (value) => ((value * 100) / quantity).toFixed(0)
          : () => "0";

      return [
        i + 1,
        item?.poultry?.unitName || "",
        item?.hall || "",
        item?.period || "",
        formatJustDate(item?.createDate),
        formatJustDate(item?.date),
        item?.chickenBreed || "",
        item?.age || "",
        quantity,
        `${losses} (%${percentage(losses)})`,
        killedNumber + ` (%${percentage(killedNumber)})`,
        `${leftOver} (%${percentage(leftOver)})`,
      ];
    });

    setDataTableArchuved(b);
  }, [avicultureHatchings]);

  const formik = useFormik({
    initialValues: {
      noChicken: "",
      slaughterDate: moment(Date()).format("YYYY-MM-DD hh:mm:ss"),
      race: "آرین",
      weight: "",
    },
    validationSchema: Yup.object({
      noChicken: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
      weight: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا وزن را وارد کنید!"),
    }),
  });

  useEffect(() => {
    formik.validateForm();
  }, []);

  return (
    <Grid container gap={SPACING.MEDIUM} direction="column" xs={12}>
      <Grid
        container
        gap={SPACING.SMALL}
        justifyContent={{ xs: "center", lg: "space-between" }}
        alignSelf="center"
        alignItems="center"
        xs={12}
        direction={{ xs: "column", lg: "row" }}
      >
        <Grid
          container
          xs={12}
          alignItems={"start"}
          gap={SPACING.SMALL}
          direction={"column"}
        >
          <Grid
            width="100%"
            container
            alignItems="center"
            justifyContent="space-between"
          >
            <Grid>
              <Button
                className="first-step"
                variant={"contained"}
                disabled={true}
                onClick={() => {
                  dispatch(
                    DRAWER({
                      title: "ثبت اطلاعات جوجه ریزی",
                      right: !(window.innerWidth <= 600),
                      bottom: window.innerWidth <= 600,
                      content: <AvicultureNewHatching />,
                    })
                  );
                }}
              >
                ثبت جوجه ریزی جدید
              </Button>
            </Grid>

            <Grid>
              {/* <Button
                onClick={() => setIsTourOpen(!isTourOpen)}
                variant="outlined"
                endIcon={<HelpOutlineIcon />}
              >
                راهنما
              </Button> */}
            </Grid>
          </Grid>
          <Tour
            steps={steps}
            isOpen={isTourOpen}
            onRequestClose={() => setIsTourOpen(false)}
            styles={{
              popover: (base) => ({
                ...base,
                borderRadius: "10px",
                "--reactor-accent": "red",
              }),
            }}
          />
          <Grid width="100%" className="second">
            <AdvancedTable
              name="دوره های فعال جوجه ریزی"
              data={dataTable}
              columns={[
                "ردیف",
                "نام فارم",
                "سالن",
                "دوره جوجه ریزی",
                "تاریخ ثبت جوجه ریزی",
                "تاریخ جوجه ریزی",
                "نژاد",
                "سن",
                "تعداد جوجه ریزی",
                "تلفات دوره",
                "کشتار شده",
                "مانده برای کشتار",
                "اقدام",
              ]}
            />
          </Grid>

          <Grid mt={SPACING.SMALL} width="100%" className="second">
            <AdvancedTable
              name="بایگانی جوجه ریزی"
              data={dataTableArchived}
              columns={[
                "ردیف",
                "نام فارم",
                "سالن",
                "دوره جوجه ریزی",
                "تاریخ ثبت جوجه ریزی",
                "تاریخ جوجه ریزی",
                "نژاد",
                "سن",
                "تعداد جوجه ریزی",
                "تلفات دوره",
                "کشتار شده",
                "مانده در سالن",
              ]}
            />
          </Grid>
        </Grid>
      </Grid>
    </Grid>
  );
};
