import {
  TimelineConnector,
  TimelineContent,
  TimelineDot,
  TimelineItem,
  TimelineOppositeContent,
  TimelineSeparator,
} from "@mui/lab";
import {
  Autocomplete,
  Button,
  FormControl,
  FormHelperText,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Typography,
} from "@mui/material";
import React, { useState } from "react";
import { PropTypes } from "prop-types";
import { Grid } from "../../../../components/grid/Grid";
import { useSlaughterHouseCars } from "../../hooks/useSlaughterHouseCars";
import { SPACING } from "../../../../data/spacing";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { useEffect } from "react";
// import { useAcceptedSlaughterRequest } from "../../hooks/useAcceptedSlaughterRequest";
import { useDispatch } from "react-redux";
import { postSlaughterCarAllocation } from "../../services/postSlaughterCarAllocation";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getAllocationInformation } from "../../services/get-allocation-information";
import { getAcceptedSlaughterRequest } from "../../services/getAcceptedSlaughterRequest";
import { useParams } from "react-router-dom";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { slaughterGetActiveRequests } from "../../../slaughter-house/services/slaughter-get-active-requests";
import { slaughterGetAllocatedCarsService } from "../../../slaughter-house/services/slaughter-get-allocated-cars";
import { slaughterGetExlusiveKillers } from "../../services/slaughterGetExlusiveKillers";
import { provincePolicyGetMaximumBarQuantityStatus } from "../../../province/services/province-policy-get-maximum-bar-quantity";

const SlaughterAssignCar = ({
  poultryRequestKey,
  provinceAllocationLimit,
  killRequestKey,
  killHouseKey,
  // killHouseName,
  killHouseCheckKey,
  indexWeight,
  item,
}) => {
  const file = {};
  const [openNotif] = useContext(AppContext);
  const slaughterHouseCars = useSlaughterHouseCars(
    poultryRequestKey,
    killHouseKey,
    killRequestKey
  );

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

  const [maximumQuantity, setMaximumQuantity] = useState(false);
  const fetchData = () => {
    dispatch(provincePolicyGetMaximumBarQuantityStatus()).then((r) => {
      setMaximumQuantity(r.payload.data);
    });
  };

  useEffect(() => {
    fetchData();
  }, []);

  const { id } = useParams();
  const buttonText =
    getRoleFromUrl() === "ProvinceOperator"
      ? "ثبت اطلاعات خودرو بجای کشتارگاه"
      : "ثبت اطلاعات خودرو";

  // const killHouseCheckKey = acceptedSlaughterRequests.filter(
  //   (item) => item.quantity > 0
  // )[0]?.killHouseCheckKey;

  // useEffect(() => {
  //   const d = acceptedSlaughterRequests?.reduce(
  //     (total, item) => (item.quantity > total ? item.quantity : total),
  //     0
  //   );
  //   setLimit(d);
  // }, [acceptedSlaughterRequests]);

  const getMaxLimit = () => {
    return maximumQuantity?.allow ? maximumQuantity?.limitation : 3100;
  };
  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      // selectedRequest: "",
      quantity: "",
      car: "",
      realCar: "",
      shippingCode: "",
    },
    validationSchema: Yup.object({
      // selectedRequest: Yup.string().required("این فیلد اجباری است!"),
      quantity: Yup.number("یک عدد وارد کنید")
        .typeError("لطفا ظرفیت را به عدد وارد کنید!")
        .required("این فیلد اجباری است!")
        .min(1, "یک مقدار مجاز وارد کنید!")
        .max(
          getMaxLimit(),
          `حداکثر میزان تخصیص به ماشین ${getMaxLimit()} قطعه میباشد`
        ),
      shippingCode: Yup.string().required("این فیلد اجباری است!"),
      // .test("len", "ظرفیت بیشتر از حد مجاز است!", (val, context) => {
      //   return context.originalValue && context.originalValue <= limit;
      // }),
      car: Yup.object().required("این فیلد اجباری است!"),
      realCar: Yup.object(),
    }),
  });

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

  useEffect(() => {
    if (file.killHouseWinner) {
      formik.setFieldValue("selectedRequest", "not required");
    }
  }, []);

  useEffect(() => {
    if (file.killHouseWinner) {
      formik.setFieldValue("selectedRequest", "not required");
    }
  }, []);

  // const carsOptions = slaughterHouseCars?.map((car, i) => {
  //   let carType = "اختصاصی";
  //   if (car.type === "exclusive") {
  //     carType = "اختصاصی";
  //   } else if (car.type === "rental") {
  //     carType = "اجاره ای";
  //   }
  //   const carLbl = `${car.driverName} (${car.driverMobile}) ${car.typeCar} پلاک ${car.pelak} ظرفیت ${car.capocity} قطعه (${carType})`;
  //   // const carLbl = ` ${car.driverName} (${car.driverMobile}) ${car.typeCar} ${car.typeWeight} پلاک ${car.pelak} ظرفیت ${car.capocity} قطعه `;

  //   return (
  //     <MenuItem disabled={car.busy} key={i} value={car}>
  //       {carLbl}
  //     </MenuItem>
  //   );
  // });

  const [chooseRealCar] = useState(false);

  // const handleChange = (event) => {
  //   setChooseRealCar(!chooseRealCar);
  // };

  const [exclusiveKillers, setExclusiveKillers] = useState();
  const [selectedOption, setSelectedOption] = useState();
  useEffect(() => {
    if (item?.exclusiveKiller) {
      dispatch(slaughterGetExlusiveKillers()).then((r) => {
        setExclusiveKillers(r.payload.data);
      });
    }
  }, []);

  const handleOptionChange = (event) => {
    setSelectedOption(event?.target.value);
  };

  const getFormValidation = () => {
    if (exclusiveKillers && exclusiveKillers.length > 0) {
      return selectedOption && formik.isValid;
    } else {
      return formik.isValid;
    }
  };

  return (
    <>
      {/* {acceptedSlaughterRequests.some((item) => item.quantity > 0) && ( */}
      <TimelineItem sx={{ alignSelf: "flex-start", width: "100%" }}>
        <TimelineSeparator>
          <TimelineDot color="secondary" />
          <TimelineConnector />
        </TimelineSeparator>
        <Grid container direction="column" flexWrap="nowrap" flex="1">
          <Grid container>
            <Grid>
              <TimelineOppositeContent
                variant="body1"
                fontWeight="bold"
                color="secondary"
              >
                انجام عملیات
              </TimelineOppositeContent>
            </Grid>
            <Grid>
              <TimelineContent color="textSecondary">
                <Typography variant="body2">
                  {/* ماشین های {killHouseName} خود را به تخصیص اختصاص دهید. */}
                </Typography>
              </TimelineContent>
            </Grid>
          </Grid>
          <Grid container justifyContent={"space-between"}>
            <Grid
              container
              alignItems="start"
              direction="column"
              gap={SPACING.SMALL}
              mt={SPACING.SMALL}
            >
              <Grid container gap={SPACING.SMALL}>
                {/* {!file.killHouseWinner && (
                  <Grid container>
                    <FormControl sx={{ minWidth: "400px" }}>
                      <InputLabel id="demo-simple-select-label">
                        درخواست های تخصیص داده شده شما
                      </InputLabel>
                      <Select
                        labelId="demo-simple-select-label"
                        id="selectedRequest"
                        label="درخواست های تخصیص داده شده شما"
                        value={formik.values.selectedRequest}
                        error={
                          formik.touched.selectedRequest
                            ? Boolean(formik.errors.selectedRequest)
                            : null
                        }
                        onChange={(e) => {
                          formik.setFieldValue(
                            "selectedRequest",
                            e.target.value
                          );
                        }}
                        onBlur={formik.handleBlur}
                      >
                        {acceptedSlaughterRequests
                          .filter((item) => item.quantity > 0)
                          .map((item, i) => {
                            return (
                              <MenuItem
                                key={i}
                                value={
                                  item.killHouseCheckKey + " " + item.quantity
                                }
                              >
                                بار با ظرفیت {item.quantity} در تاریخ{" "}
                                {format(new Date(item.date), "yyyy/MM/dd")}
                              </MenuItem>
                            );
                          })}
                      </Select>
                      <FormHelperText>
                        {formik.touched.race && Boolean(formik.errors.race)
                          ? formik.errors.race
                          : null}
                      </FormHelperText>
                    </FormControl>
                  </Grid>
                )} */}

                <Grid xs={12}>
                  <Typography sx={{ fontSize: "12px" }} color="secondary">
                    خودرو دارای کد بهداشتی حمل
                  </Typography>
                </Grid>
                <Grid container direction="column" alignItems="start">
                  <FormControl sx={{ width: "300px" }}>
                    <Autocomplete
                      options={slaughterHouseCars || []}
                      getOptionLabel={(car) => {
                        if (car) {
                          const carType =
                            car.type === "exclusive" ? "اختصاصی" : "اجاره ای";
                          return `${car.driverName} (${car.driverMobile}) ${car.typeCar} پلاک ${car.pelak} (${carType})`;
                        }
                        return "";
                      }}
                      value={formik.values.car}
                      onChange={(e, car) => {
                        formik.setFieldValue("car", car);
                        formik.setFieldValue(
                          "shippingCode",
                          car ? car.healthCode : ""
                        );
                      }}
                      onBlur={formik.handleBlur}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="انتخاب خودرو و راننده"
                          error={
                            formik.touched.car
                              ? Boolean(formik.errors.car)
                              : null
                          }
                        />
                      )}
                    />

                    <FormHelperText>
                      {formik.touched.car && Boolean(formik.errors.car)
                        ? formik.errors.car
                        : null}
                    </FormHelperText>
                  </FormControl>
                  {/* <Grid container alignItems="center" xs={12} gap={0}>
                    <FormControlLabel
                      control={<Checkbox checked={chooseRealCar} />}
                      onChange={handleChange}
                      label="انتخاب خودرو واقعی برای حمل مرغ زنده (اختیاری)"
                      componentsProps={{
                        typography: {
                          sx: { fontSize: "12px", color: "red" },
                        },
                      }}
                    />
                  </Grid> */}

                  {chooseRealCar && (
                    <FormControl sx={{ width: "300px" }}>
                      <Autocomplete
                        options={slaughterHouseCars || []}
                        getOptionLabel={(car) => {
                          if (car) {
                            const carType =
                              car.type === "exclusive" ? "اختصاصی" : "اجاره ای";
                            return `${car.driverName} (${car.driverMobile}) ${car.typeCar} پلاک ${car.pelak} ظرفیت ${car.capocity} قطعه (${carType})`;
                          }
                          return "";
                        }}
                        value={formik.values.realCar}
                        onChange={(e, car) => {
                          formik.setFieldValue("realCar", car);
                        }}
                        onBlur={formik.handleBlur}
                        renderInput={(params) => (
                          <TextField
                            {...params}
                            label="انتخاب خودرو و راننده"
                            error={
                              formik.touched.car
                                ? Boolean(formik.errors.realCar)
                                : null
                            }
                          />
                        )}
                      />

                      <FormHelperText>
                        {formik.touched.realCar &&
                        Boolean(formik.errors.realCar)
                          ? formik.errors.realCar
                          : null}
                      </FormHelperText>
                    </FormControl>
                  )}

                  {exclusiveKillers?.length > 0 && (
                    <>
                      <Grid xs={12}>
                        <Typography
                          sx={{ fontSize: "12px" }}
                          color="red"
                          mb={1}
                          mt={1}
                        >
                          انتخاب کشتارکن جهت تخصیص
                        </Typography>
                      </Grid>
                      <FormControl>
                        <InputLabel id="demo-simple-select-label">
                          انتخاب کشتارکن (اجباری)
                        </InputLabel>
                        <Select
                          label="کشتارکن"
                          // disabled={disableSelect}
                          // label="Select Option"
                          value={selectedOption}
                          onChange={handleOptionChange}
                        >
                          {exclusiveKillers?.map((item, i) => {
                            return (
                              <MenuItem key={i} value={item?.key}>
                                {item?.name}
                              </MenuItem>
                            );
                          })}
                        </Select>
                      </FormControl>
                    </>
                  )}
                  <Grid
                    container
                    textAlign="start"
                    direction="column"
                    mt={SPACING.TINY}
                  >
                    {slaughterHouseCars
                      .filter((item) => item.busy)
                      .map((car, i) => {
                        const carLbl = `راننده ${car.driverName} ${car.typeCar} با پلاک ${car.pelak} جهت حمل بار کشتارگاه دیگری رزرو شده است.`;
                        // const carLbl = ` ${car.driverName} (${car.driverMobile}) ${car.typeCar} ${car.typeWeight} پلاک ${car.pelak} ظرفیت ${car.capocity} قطعه `;
                        return (
                          <Grid key={"car" + i}>
                            <Typography variant="caption">{carLbl}</Typography>
                          </Grid>
                        );
                      })}
                  </Grid>
                </Grid>
                <Grid>
                  <TextField
                    allowLeadingZeros
                    thousandSeparator=","
                    id="shippingCode"
                    label="کد بهداشتی حمل و نقل"
                    value={formik.values.shippingCode}
                    error={
                      formik.touched.shippingCode
                        ? Boolean(formik.errors.shippingCode)
                        : null
                    }
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    helperText={
                      formik.touched.shippingCode &&
                      Boolean(formik.errors.shippingCode)
                        ? formik.errors.shippingCode
                        : null
                    }
                    variant="outlined"
                  />
                </Grid>
                <Grid>
                  <TextField
                    allowLeadingZeros
                    thousandSeparator=","
                    id="quantity"
                    label="ظرفیت (قطعه)"
                    value={formik.values.quantity}
                    error={
                      formik.touched.quantity
                        ? Boolean(formik.errors.quantity)
                        : null
                    }
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    helperText={
                      formik.touched.quantity && Boolean(formik.errors.quantity)
                        ? formik.errors.quantity
                        : null
                    }
                    autoComplete="current-password"
                    variant="outlined"
                  />
                  <Grid
                    container
                    mt={SPACING.TINY}
                    gap={SPACING.TINY}
                    alignItems="center"
                  >
                    <Typography
                      color={(prop) => prop.palette.grey["A700"]}
                      variant={"caption"}
                    >
                      ظرفیت مجاز ماشین:
                    </Typography>
                    <Typography variant={"button"}>
                      {getMaxLimit()} قطعه
                    </Typography>
                  </Grid>
                  <Grid
                    container
                    mt={SPACING.TINY}
                    gap={SPACING.TINY}
                    alignItems="center"
                  >
                    <Typography
                      color={(prop) => prop.palette.grey["A700"]}
                      variant={"caption"}
                    >
                      باقی مانده:
                    </Typography>
                    <Typography variant={"button"}>
                      {provinceAllocationLimit -
                        Number(formik.values.quantity) >=
                      0
                        ? provinceAllocationLimit -
                          Number(formik.values.quantity)
                        : 0}{" "}
                      قطعه
                    </Typography>
                  </Grid>
                  <Grid
                    container
                    mt={SPACING.TINY}
                    gap={SPACING.TINY}
                    alignItems="center"
                  >
                    <Typography
                      color={(prop) => prop.palette.grey["A700"]}
                      variant={"caption"}
                    >
                      مازاد:
                    </Typography>
                    <Typography variant={"button"}>
                      {Number(formik.values.quantity) > provinceAllocationLimit
                        ? Math.abs(
                            Number(formik.values.quantity) -
                              provinceAllocationLimit
                          )
                        : 0}{" "}
                      قطعه
                    </Typography>
                  </Grid>
                  <Grid
                    container
                    mt={SPACING.TINY}
                    gap={SPACING.TINY}
                    alignItems="center"
                  >
                    <Typography
                      color={(prop) => prop.palette.grey["A700"]}
                      variant={"caption"}
                    >
                      وزن تقریبی هرقطعه مرغ:
                    </Typography>
                    <Typography variant={"button"}>
                      {indexWeight.toLocaleString()} کیلوگرم
                    </Typography>
                  </Grid>
                </Grid>
                <Grid container alignItems="start" gap={SPACING.SMALL}>
                  <Grid
                    container
                    mt={SPACING.TINY}
                    gap={SPACING.TINY}
                    alignItems="center"
                  >
                    <Typography color={(prop) => prop.palette.grey["A700"]}>
                      =
                    </Typography>
                    <Typography
                      color={(prop) => prop.palette.grey["A700"]}
                      variant={"caption"}
                    >
                      وزن تقریبی بار:
                    </Typography>
                    <Typography variant={"button"}>
                      {(
                        Number(formik.values.quantity) * indexWeight
                      ).toLocaleString()}{" "}
                      کیلوگرم
                    </Typography>
                  </Grid>
                </Grid>
              </Grid>
              <Grid container>
                <Button
                  size={"large"}
                  variant={"contained"}
                  disabled={!getFormValidation()}
                  onClick={() => {
                    dispatch(LOADING_START());
                    let reqObj = {};
                    if (file.killHouseWinner) {
                      reqObj = {
                        winner_key: file.killHouseWinner.killHouseWinnerKey,
                        quantity: Number(formik.values.quantity),
                        killer_key: selectedOption ? selectedOption : null,
                        car: {
                          id: formik.values.car.id,
                          key: formik.values.car.key,
                          driver_name: formik.values.car.driverName,
                          driver_mobile: formik.values.car.driverMobile,
                          name: formik.values.car.name,
                          type_car: formik.values.car.typeCar,
                          type_weight: formik.values.car.typeWeight,
                          pelak: formik.values.car.pelak,
                          capocity: formik.values.car.capocity,
                          weight_without_load:
                            formik.values.car.weightWithoutLoad,
                          health_code: formik.values.car.helathCode,
                        },
                      };
                    } else {
                      reqObj = {
                        killer_key: selectedOption ? selectedOption : null,
                        kill_house_check_key: killHouseCheckKey,
                        quantity: Number(formik.values.quantity),
                        traffic_code: formik.values.shippingCode,
                        real_car_key: formik.values.realCar.key,
                        role: getRoleFromUrl(),
                        car: {
                          id: formik.values.car.id,
                          key: formik.values.car.key,
                          driver_name: formik.values.car.driverName,
                          driver_mobile: formik.values.car.driverMobile,
                          name: formik.values.car.name,
                          type_car: formik.values.car.typeCar,
                          type_weight: formik.values.car.typeWeight,
                          pelak: formik.values.car.pelak,
                          capocity: formik.values.car.capocity,
                          weight_without_load:
                            formik.values.car.weightWithoutLoad,
                          health_code: formik.values.car.helathCode,
                        },
                      };
                    }
                    dispatch(postSlaughterCarAllocation(reqObj)).then((r) => {
                      dispatch(LOADING_END());
                      if (r.payload.error) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: r.payload.error,
                          severity: "error",
                        });
                      } else {
                        dispatch(LOADING_END());
                        // getFileFromApi(roles, id, dispatch);
                        dispatch(
                          slaughterGetActiveRequests({
                            isCar: true,
                            selectedDate1,
                            selectedDate2,
                          })
                        );
                        dispatch(
                          slaughterGetAllocatedCarsService({
                            selectedDate1,
                            selectedDate2,
                          })
                        );
                        dispatch(getAcceptedSlaughterRequest({ id }));
                        dispatch(
                          getAllocationInformation({
                            key: poultryRequestKey,
                          })
                        );
                        dispatch(getAcceptedSlaughterRequest());

                        dispatch(
                          DRAWER({
                            right: false,
                            bottom: false,
                            top: false,
                            content: null,
                          })
                        );
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "عملیات با موفقیت انجام شد.",
                          severity: "success",
                        });
                      }
                    });
                  }}
                >
                  {buttonText}
                </Button>
              </Grid>

              {/* <Grid
                container
                direction={"column"}
                alignItems={"start"}
                gap={SPACING.SMALL}
              >
                <Grid>
                  <Typography
                    variant={"body1"}
                    fontWeight={"bold"}
                    color={"primary"}
                  >
                    ماشین های ثبت شده
                  </Typography>
                </Grid>
                <Grid>
                  {!file.killHouseWinner &&
                    acceptedSlaughterRequests?.map((item, i) => {
                      const head = `برای سفارش ${item.orderCode} با باقی مانده ظرفیت ${item.quantity} قطعه `;
                      const killHouseAssignments =
                        item.killHouseAssignments.map((assignment, index) => {
                          const barItem = `کدبار ${assignment.barcod} تعداد ${assignment.quantity} قطعه با ماشین ${assignment.cars.typeCar} راننده ${assignment.cars.driverName}`;
                          return (
                            <Grid key={i + index} textAlign={"start"}>
                              <Grid color={(prop) => prop.palette.grey["A700"]}>
                                <ListItem>
                                  <ListItemIcon>
                                    <CircleIcon />
                                  </ListItemIcon>
                                  <ListItemText primary={barItem} />
                                </ListItem>
                              </Grid>
                            </Grid>
                          );
                        });
                      return (
                        <Grid key={"acceptedSlaughterRequests" + i}>
                          <Grid container gap={SPACING.SMALL}>
                            <Typography variant={"body2"}>{head}</Typography>
                          </Grid>
                          <List>{killHouseAssignments}</List>
                        </Grid>
                      );
                    })}

                  {file.killHouseWinner &&
                    file.auction?.map((item, i) => {
                      const head = `برای سفارش ${item.orderCode} با باقی مانده ظرفیت ${file.killHouseWinner.quantity} قطعه `;
                      const barItem = `کدبار ${item.barcod} تعداد ${item.quantity} قطعه با ماشین ${item.cars.typeCar} راننده ${item.cars.driverName}`;
                      const returnItem = (
                        <Grid key={i + i} textAlign={"start"}>
                          <Grid color={(prop) => prop.palette.grey["A700"]}>
                            <ListItem>
                              <ListItemIcon>
                                <CircleIcon />
                              </ListItemIcon>
                              <ListItemText primary={barItem} />
                            </ListItem>
                          </Grid>
                        </Grid>
                      );
                      return (
                        <Grid key={"acceptedSlaughterRequests" + i}>
                          <Grid container gap={SPACING.SMALL}>
                            <Typography variant={"body2"}>{head}</Typography>
                          </Grid>
                          <List>{returnItem}</List>
                        </Grid>
                      );
                    })}
                </Grid>
              </Grid> */}
            </Grid>
          </Grid>
        </Grid>
      </TimelineItem>
      {/* )} */}
    </>
  );
};
SlaughterAssignCar.propTypes = {
  file: PropTypes.object,
  provinceAllocationLimit: PropTypes.any,
};

export default SlaughterAssignCar;
