import {
  Button,
  Checkbox,
  TableCell,
  TableRow,
  TextField,
  Tooltip,
} from "@mui/material";
import { useFormik } from "formik";
import React, { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
// import { useParams } from "react-router-dom";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
// import useUserProfile from "../../../authentication/hooks/useUserProfile";
// import { getFileFromApi } from "../../hooks/useRequestFile";
import { getAllocationInformation } from "../../services/get-allocation-information";
import { provinceDoAllocation } from "../../services/province-do-allocation";
import * as Yup from "yup";
// import useUserProfile from "../../../authentication/hooks/useUserProfile";
// import { useParams } from "react-router-dom";
import { getSlaughterHousesRequest } from "../../services/getSlaughterHousesRequest";
// import useUserProfile from "../../../authentication/hooks/useUserProfile";
// import { useParams } from "react-router-dom";
import { provinceGetAllRequests } from "../../../province/services/province-get-all-requests";
import { getFileFromApi } from "../../hooks/useRequestFile";
import useUserProfile from "../../../authentication/hooks/useUserProfile";
import { ProvinceEditKillCapacityForm } from "../../../province/components/province-edit-kill-capacity-form/ProvinceEditKillCapacityForm";
// import { getSlaughterHousesRequest } from "../../services/getSlaughterHousesRequest";
import VerifiedIcon from "@mui/icons-material/Verified";

const validationSchema = Yup.object().shape({
  quantity: Yup.number()
    .required("تعداد اجباری است.")
    .positive("تعداد باید بالاتر از 0 باشد.")
    .integer("تعداد باید عدد باشد."),
});

export function SlaghterHouseRequestAllocationItem({
  slaughterHouseReq,
  provinceCheckRequestKey,
  poultryRequestId,
  poultryRequestKey,
  // handleFileQuantity,
  handleAllEntredQauntity,
  allEntredQauntity,
  name,
  file,
  avgLast4KillhousesWeight,
  defaultValueForAllocate,
  updateTable,
}) {
  const [openNotif, , selectedDate1] = useContext(AppContext);

  const [roles] = useUserProfile();
  // const { id } = useParams();
  const dispatch = useDispatch();
  const [checked, setChecked] = useState(false);

  const handleCheckboxChange = (event) => {
    setChecked(event.target.checked);
  };

  const formik = useFormik({
    initialValues: {
      quantity: slaughterHouseReq.remainQuantity,
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      dispatch(LOADING_START());
      dispatch(
        provinceDoAllocation({
          kill_request_key: slaughterHouseReq.key,
          province_check_request_key: provinceCheckRequestKey,
          quantity: values.quantity,
          payment_type: "نقدی",
        })
      ).then((r) => {
        dispatch(LOADING_END());
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          setChecked(false);
          // handleAllEntredQauntity(null);
          getFileFromApi(roles, poultryRequestId, dispatch);
          dispatch(provinceGetAllRequests(selectedDate1));
          dispatch(getSlaughterHousesRequest({ key: poultryRequestKey }));
          dispatch(getAllocationInformation({ key: poultryRequestKey }));
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
          updateTable();
        }
      });
    },
  });

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

  useEffect(() => {
    const num =
      Number(defaultValueForAllocate) < 0 ? 0 : Number(defaultValueForAllocate);
    formik.setFieldValue("quantity", num);
  }, [defaultValueForAllocate]);

  useEffect(() => {
    if (checked) {
      const num =
        Number(formik.values.quantity) < 0 ? 0 : Number(formik.values.quantity);
      handleAllEntredQauntity({
        ...allEntredQauntity,
        [name]: num,
      });
    } else {
      handleAllEntredQauntity({
        ...allEntredQauntity,
        [name]: Number(0),
      });
    }
  }, [formik.values.quantity, checked]);

  const { poultryRequestIndexWeight } = useSelector((state) => state.fileSlice);
  const avgPoultryRequestsWeight = poultryRequestIndexWeight?.ave;
  const fileWeight = file?.poultry?.IndexWeight;
  // let weightProirity;
  if (
    fileWeight > avgPoultryRequestsWeight &&
    slaughterHouseReq.firstAverageWeight < avgLast4KillhousesWeight
  ) {
    // weightType = "high";
    // weightProirity = true;
  } else if (
    fileWeight < avgPoultryRequestsWeight &&
    slaughterHouseReq.firstAverageWeight > avgLast4KillhousesWeight
  ) {
    // weightType = "low";
    // weightProirity = true;
  } else {
    // weightProirity = false;
  }

  const allocationBtnDisabled =
    checked && formik.isValid && defaultValueForAllocate > 0;

  const buyerNamePrefix = slaughterHouseReq?.killHouse?.killer
    ? "کشتارکن"
    : "کشتارگاه";

  return (
    <TableRow>
      <TableCell style={{ alignItems: "center", textAlign: "center" }}>
        <Grid container direction="row" flexWrap="nowrap" alignItems="center">
          <Checkbox
            key={slaughterHouseReq?.killHouse?.name}
            checked={checked}
            onChange={handleCheckboxChange}
          />
          {buyerNamePrefix + " " + slaughterHouseReq?.killHouse?.name}

          {slaughterHouseReq?.priority && (
            <Tooltip title={"پیشنهادی مرغدار"} placement="left-start">
              <VerifiedIcon color="success" />
            </Tooltip>
          )}
        </Grid>
      </TableCell>
      <TableCell style={{ alignItems: "center", textAlign: "center" }}>
        {slaughterHouseReq?.killHouse?.killHouseOperator?.user?.fullname} (
        {slaughterHouseReq?.killHouse?.killHouseOperator?.user?.mobile})
      </TableCell>
      <TableCell style={{ alignItems: "center", textAlign: "center" }}>
        <DisabledWrap key={"vv"} checked={checked}>
          {slaughterHouseReq.firstAverageWeight} کیلوگرم
        </DisabledWrap>
      </TableCell>
      {/* <TableCell style={{ alignItems: "center", textAlign: "center" }}>
        <DisabledWrap key={"vv"} checked={checked}>
          {slaughterHouseReq.secondAverageWeight} کیلوگرم
        </DisabledWrap>
      </TableCell> */}
      {/* <TableCell style={{ alignItems: "center", textAlign: "center" }}>
        {weightProirity ? (
          <Typography color={"green"}>دارد</Typography>
        ) : (
          <Typography color={"red"}>ندارد</Typography>
        )}
      </TableCell>
      <TableCell style={{ alignItems: "center", textAlign: "center" }}>
        {slaughterHouseReq?.killHouse?.systemAddress?.city?.name ===
        file?.poultry?.poultryCity ? (
          <Typography color={"green"}>دارد</Typography>
        ) : (
          <Typography color={"red"}>ندارد</Typography>
        )}
      </TableCell>
      <TableCell style={{ alignItems: "center", textAlign: "center" }}>
        {slaughterHouseReq.debt ? (
          <Typography color={"green"}>دارد</Typography>
        ) : (
          <Typography color={"red"}>ندارد</Typography>
        )}
      </TableCell>
      <TableCell style={{ alignItems: "center", textAlign: "center" }}>
        <Typography>
          {slaughterHouseReq?.factorAmount?.toLocaleString() + " ﷼"}
        </Typography>
      </TableCell>
      <TableCell style={{ alignItems: "center", textAlign: "center" }}>
        <Typography>
          {slaughterHouseReq?.factorDeposit?.toLocaleString() + " ﷼"}
        </Typography>
      </TableCell> */}
      <TableCell style={{ alignItems: "center", textAlign: "center" }}>
        <DisabledWrap key={"vv"} checked={checked}>
          {slaughterHouseReq?.killCapacity}
          <Button
            aria-label="delete"
            color="primary"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "اضافه کردن به درخواست کشتارگاه",
                  content: (
                    <ProvinceEditKillCapacityForm
                      poultryRequestKey={poultryRequestKey}
                      killRequestKey={slaughterHouseReq?.key}
                      killCapacity={slaughterHouseReq.killCapacity}
                      updateTable={updateTable}
                    />
                  ),
                })
              );
            }}
          >
            ویرایش
          </Button>
        </DisabledWrap>
      </TableCell>
      <TableCell style={{ alignItems: "center", textAlign: "center" }}>
        <DisabledWrap key={"vv"} checked={checked}>
          {slaughterHouseReq?.remainQuantity?.toLocaleString()}
        </DisabledWrap>
      </TableCell>
      <TableCell style={{ alignItems: "center", textAlign: "center" }}>
        <DisabledWrap key={"vv"} checked={checked}>
          {slaughterHouseReq?.numberOfAllocated?.toLocaleString()}
        </DisabledWrap>
      </TableCell>
      <TableCell style={{ alignItems: "center", textAlign: "center" }}>
        <DisabledWrap key={"vv"} checked={checked}>
          <Grid key={slaughterHouseReq?.killHouse?.name}>
            <TextField
              disabled={!checked}
              label="حجم"
              type="number"
              style={{ width: "80%" }}
              inputProps={{
                min: 0,
                step: 1,
              }}
              fullWidth
              id="quantity"
              value={formik.values.quantity}
              onChange={formik.handleChange}
              error={formik.touched.quantity && Boolean(formik.errors.quantity)}
              helperText={formik.touched.quantity && formik.errors.quantity}
            />
          </Grid>
        </DisabledWrap>
      </TableCell>
      <TableCell style={{ alignItems: "center", textAlign: "center" }}>
        <DisabledWrap key={"vv"} checked={checked}>
          <Button
            key={slaughterHouseReq?.killHouse?.name}
            variant="contained"
            type="submit"
            color="primary"
            disabled={!allocationBtnDisabled}
            onClick={formik.handleSubmit}
          >
            تخصیص
          </Button>
        </DisabledWrap>
      </TableCell>
    </TableRow>
  );
}

const DisabledWrap = ({ children, checked }) => {
  return <Grid style={{ opacity: !checked ? 0.5 : 1 }}>{children}</Grid>;
};
