import {
  Button,
  Checkbox,
  // Checkbox,
  FormControl,
  FormControlLabel,
  // FormControlLabel,
  // FormGroup,
  // FormHelperText,
  Grid,
  InputLabel,
  ListItem,
  ListItemIcon,
  ListItemText,
  MenuItem,
  Select,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import { SPACING } from "../../../../data/spacing";
import { useFormik } from "formik";
import moment from "moment";
import { Yup } from "../../../../lib/yup/yup";

import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { DialogAlert } from "../../../../components/dialog-alert/DialogAlert";
import useUserProfile from "../../../authentication/hooks/useUserProfile";
import DoneIcon from "@mui/icons-material/Done";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";

import { provinceGetPricing } from "../../../province/services/province-get-pricing";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { slaughterNewRequest } from "../../../slaughter-house/services/slaughter-new-request";
import { inspectorGetKillHousesService } from "../../services/inspector-get-kill-houses";
import { getSlaughtersKillRequestService } from "../../../city/services/get-slaughters-kill-request";

export const InspectorKillHouseNewRequest = () => {
  const [openNotif, , selectedDate1, , selectedDate2, ,] =
    useContext(AppContext);
  const dispatch = useDispatch();
  const [, userProfile] = useUserProfile();
  const { inspectorGetKillHouses } = useSelector(
    (state) => state.inspectorSlice
  );
  const [killhouses, setKillhouses] = useState([]);
  const [onlyKillhouses, setOnlyKillhouses] = useState([]);
  const [isKiller, setIsKiller] = useState(false);

  useEffect(() => {
    const d = inspectorGetKillHouses?.map((item) => {
      return { name: item.name, key: item.key, killer: item.killer };
    });
    setKillhouses(d);
  }, [inspectorGetKillHouses]);

  useEffect(() => {
    if (isKiller === "true") {
      const c = inspectorGetKillHouses
        ?.filter((item) => item.killer === false)
        ?.map((item) => {
          return { name: item.name, key: item.key, killer: item.killer };
        });
      setOnlyKillhouses(c);
    }
  }, [inspectorGetKillHouses, isKiller]);

  const formik = useFormik({
    initialValues: {
      capacity: "",
      recieveTime: "",
      selectedKillhouse: "",
      selectedKillerKillhouse: "",
      race: "",
      sellType: {
        cash: true,
        haveTime: false,
      },
      weightType: {
        under2AndHalf: false,
        over2AndHalf: false,
      },
      recieveDate: moment(Date()).format("YYYY-MM-DD hh:mm:ss"),
      isAccepted: getRoleFromUrl() !== "KillHouse" ? true : false,
      indexWeight: "",
    },
    validationSchema: Yup.object({
      capacity: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
      selectedKillhouse: Yup.string().required("این فیلد اجباری است!"),
      selectedKillerKillhouse:
        isKiller === "true"
          ? Yup.string().required("این فیلد اجباری است!")
          : Yup.string(),
      recieveTime: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا وزن را وارد کنید!"),
      sellType: Yup.object()
        .test("sellType", "نحوه فروش را انتخاب کنید!", (val, context) => {
          return (
            context.originalValue &&
            Object.values(context.originalValue).some((item) => item === true)
          );
        })
        .required("این فیلد اجباری است!"),
      isAccepted: Yup.boolean()
        .test("req", "باید تعهد نامه را بپذیرید!", (val, context) => {
          return context.originalValue && context.originalValue === true;
        })
        .required("این فیلد اجباری است!"),
      // weightType: Yup.object()
      //   .test("weightType", "وزن را انتخاب کنید!", (val, context) => {
      //     return (
      //       context.originalValue &&
      //       Object.values(context.originalValue).some((item) => item === true)
      //     );
      //   })
      //   .required("این فیلد اجباری است!"),
    }),
  });

  const penaltyPrice = formik.values.capacity * 1000;
  const dialogContent = (
    <>
      <Typography variant="body1">
        اینجانب {userProfile?.fullname} موافقت خود را نسبت به موارد ذکر شده
        اعلام می نمایم.
      </Typography>
      <ListItem>
        <ListItemIcon>
          <DoneIcon />
        </ListItemIcon>
        <ListItemText
          primary={`بر اساس این توافق نامه در صورت لغو کشتار ${formik.values.capacity} قطعه
          مرغ ${penaltyPrice} ریال جریمه خواهم شد.`}
        />
      </ListItem>
    </>
  );

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

  // const handleSellTypeChange = (event) => {
  //   formik.setFieldValue("sellType", {
  //     ...formik.values.sellType,
  //     [event.target.name]: event.target.checked,
  //   });
  // };
  // const handleWeightTypeChange = (event) => {
  //   formik.setFieldValue("weightType", {
  //     ...formik.values.weightType,
  //     [event.target.name]: event.target.checked,
  //   });
  // };

  const [checkedSms, setCheckedSms] = useState(true);

  const handleChangeCheckedSms = (event) => {
    setCheckedSms(event.target.checked);
  };

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

  return (
    <>
      <Grid
        className="slaughter-new-request-form"
        container
        gap={SPACING.SMALL}
        direction="column"
        flex="1"
        justifyContent="space-between"
      >
        <Grid container style={{ width: "300px" }} justifyContent="center">
          {/* <CustomCard
            title="قیمت روز مرغ"
            value={
              chickenPrice +
              " - " +
              format(new Date(chickenPriceDate), "yyyy/MM/dd")
            }
          /> */}
        </Grid>
        <Grid container direction="column" gap={SPACING.SMALL}>
          <FormControl
            fullWidth
            error={
              formik.errors.selectedOption && formik.touched.selectedOption
            }
          >
            <InputLabel>انتخاب کشتارگاه یا کشتارکن</InputLabel>
            <Select
              label="انتخاب کشتارگاه یا کشتارکن"
              id="selectedKillhouse"
              name="selectedKillhouse"
              //   value={formik.values.selectedKillhouse}
              onChange={(e) => {
                const [key, killer] = e.target.value.split("#");
                formik.setFieldValue("selectedKillhouse", key);
                setIsKiller(killer);
              }}
              onBlur={formik.handleBlur}
            >
              {killhouses?.map((option) => (
                <MenuItem
                  key={option}
                  value={`${option.key + "#" + option.killer}`}
                >
                  {option.killer
                    ? `کشتارکن ${option.name}`
                    : `کشتارگاه ${option.name}`}
                </MenuItem>
              ))}
            </Select>
            {formik.errors.selectedKillhouse &&
              formik.touched.selectedKillhouse && (
                <div>{formik.errors.selectedKillhouse}</div>
              )}
          </FormControl>

          {isKiller === "true" && (
            <FormControl
              fullWidth
              error={
                formik.errors.selectedKillerKillhouse &&
                formik.touched.selectedKillerKillhouse
              }
            >
              <InputLabel>محل کشتار را انتخاب کنید</InputLabel>
              <Select
                label="محل کشتار را انتخاب کنید"
                id="selectedKillerKillhouse"
                name="selectedKillerKillhouse"
                value={formik.values.selectedKillerKillhouse}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              >
                {onlyKillhouses?.map((option) => (
                  <MenuItem key={option} value={option.key}>
                    {option.name}
                  </MenuItem>
                ))}
              </Select>
              {formik.errors.selectedKillerKillhouse &&
                formik.touched.selectedKillerKillhouse && (
                  <div>{formik.errors.selectedKillerKillhouse}</div>
                )}
            </FormControl>
          )}

          <Grid>
            <NumberInput
              allowLeadingZeros
              thousandSeparator=","
              id="capacity"
              fullWidth
              label="حجم کشتار را در روز به قطعه وارد کنید"
              variant="outlined"
              value={formik.values.capacity}
              error={
                formik.touched.capacity ? Boolean(formik.errors.capacity) : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.capacity && Boolean(formik.errors.capacity)
                  ? formik.errors.capacity
                  : null
              }
            />
          </Grid>
          <Grid>
            <FormControl fullWidth sx={{ minWidth: 210 }}>
              <InputLabel>بازه زمانی دریافت مرغ مرغدار</InputLabel>
              <Select
                id="recieveTime"
                value={formik.values.recieveTime}
                label="بازه زمانی دریافت مرغ مرغدار"
                onChange={(e) => {
                  formik.setFieldValue("recieveTime", e.target.value);
                }}
              >
                <MenuItem value={"12 - 14"}>12 - 14</MenuItem>
                <MenuItem value={"14 - 16"}>14 - 16</MenuItem>
                <MenuItem value={"16 - 18"}>16 - 18</MenuItem>
                <MenuItem value={"18 - 20"}>18 - 20</MenuItem>
                <MenuItem value={"20 - 22"}>20 - 22</MenuItem>
                <MenuItem value={"22 - 24"}>22 - 24</MenuItem>
              </Select>
            </FormControl>
          </Grid>

          <Grid>
            <DatePicker
              label="تاریخ کشتار"
              id="recieveDate"
              renderInput={(params) => <TextField {...params} />}
              value={formik.values.recieveDate}
              error={
                formik.touched.recieveDate
                  ? Boolean(formik.errors.recieveDate)
                  : null
              }
              onChange={(e) => {
                formik.setFieldValue(
                  "recieveDate",
                  moment(e).format("YYYY-MM-DD hh:mm:ss")
                );
              }}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.recieveDate && Boolean(formik.errors.recieveDate)
                  ? formik.errors.recieveDate
                  : null
              }
            />
          </Grid>
        </Grid>
        {/* <Grid>
            <Grid>
              <Typography varaint="body1">نحوه خرید</Typography>
            </Grid>
            <FormGroup>
              <FormControlLabel
                control={
                  <Checkbox
                    onChange={handleSellTypeChange}
                    name="cash"
                    value="نقدی"
                  />
                }
                label="نقدی"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    onChange={handleSellTypeChange}
                    name="haveTime"
                    value="زمان دار"
                  />
                }
                label="زمان دار (تا یک ماه)"
              />
            </FormGroup>
            <FormHelperText>
              {formik.touched.sellType && Boolean(formik.errors.sellType)
                ? formik.errors.sellType
                : null}
            </FormHelperText>
          </Grid> */}
        {/* <Grid>
            <Grid>
              <Typography varaint="body1">وزن پیشنهادی</Typography>
            </Grid>
            <FormGroup>
              <FormControlLabel
                control={
                  <Checkbox
                    onChange={handleWeightTypeChange}
                    name="under2AndHalf"
                  />
                }
                label="2 تا 2.5 کیلوگرم"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    onChange={handleWeightTypeChange}
                    name="over2AndHalf"
                  />
                }
                label="2.5 کیلوگرم به بالا"
              />
            </FormGroup>
          </Grid> */}
        <Grid>
          {getRoleFromUrl() === "KillHouse" && (
            <DialogAlert
              title="تعهد نامه"
              content={dialogContent}
              actions={
                <Grid container justifyContent="end" gap={SPACING.TINY}>
                  <Button
                    variant="outlined"
                    color="error"
                    onClick={() => {
                      formik.setFieldValue("isAccepted", false);
                    }}
                  >
                    رد
                  </Button>
                  <Button
                    variant="contained"
                    color="success"
                    onClick={() => {
                      formik.setFieldValue("isAccepted", true);
                    }}
                  >
                    موافقم
                  </Button>
                </Grid>
              }
              btnTitle={"با تعهد نامه موافق هستم!"}
              isAccepted={formik.values.isAccepted}
            />
          )}

          <Grid>
            <FormControlLabel
              style={{ fontSize: "10px" }}
              control={
                <Checkbox
                  checked={checkedSms}
                  onChange={handleChangeCheckedSms}
                />
              }
              label={
                <Tooltip title="5000 تومان" arrow>
                  <Typography variant="caption">
                    مایل به دریافت پیامک اطلاع رسانی هستم!
                  </Typography>
                </Tooltip>
              }
            />
          </Grid>
        </Grid>
        <Grid container mt={SPACING.SMALL} justifyContent="center">
          <Button
            fullWidth
            variant="contained"
            component="label"
            disabled={!formik.isValid}
            size="large"
            onClick={() => {
              dispatch(LOADING_START());
              dispatch(
                slaughterNewRequest({
                  kill_capacity: formik.values.capacity,
                  recive_time: formik.values.recieveTime,
                  recive_date: formik.values.recieveDate,
                  low_weight: formik.values.weightType.under2AndHalf,
                  high_weight: formik.values.weightType.over2AndHalf,
                  Index_weight: 2.7,
                  chicken_breed: "تعیین نشده",
                  cash: formik.values.sellType.cash,
                  credit: formik.values.sellType.haveTime,
                  sms_payment: checkedSms,
                  kill_house_key: formik.values.selectedKillhouse,
                  killer_kill_house_key: formik.values.selectedKillerKillhouse
                    ? formik.values.selectedKillerKillhouse
                    : null,
                  role: getRoleFromUrl(),
                })
              ).then((r) => {
                dispatch(
                  getSlaughtersKillRequestService({
                    selectedDate1,
                    selectedDate2,
                  })
                );
                dispatch(LOADING_END());
                if (r.payload.error) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: r.payload.error,
                    severity: "error",
                  });
                } else {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "عملیات با موفقیت انجام شد.",
                    severity: "success",
                  });
                  dispatch(
                    DRAWER({ right: false, bottom: false, content: null })
                  );
                }
              });
            }}
          >
            ثبت درخواست
          </Button>
        </Grid>
      </Grid>
    </>
  );
};
