import { SPACING } from "../../../../data/spacing";
import { Grid } from "../../../../components/grid/Grid";
import {
  Autocomplete,
  Button,
  FormControl,
  FormHelperText,
  IconButton,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { useEffect } from "react";
import moment from "moment/moment";
import { DatePicker } from "@mui/x-date-pickers";
import { useDispatch } from "react-redux";
import { useState } from "react";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import SearchIcon from "@mui/icons-material/Search";

import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { cityGetPoultryData } from "../../services/city-get-poultry-data";
import { avicultureNewHatching } from "../../../aviculture/services/aviculture-new-hatching";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { cityGetHatchings } from "../../services/city-get-hatchings";
import { reloadHatchings } from "../../../../lib/redux/slices/citySlice";

export const CityNewHatchingRequest = () => {
  const dispatch = useDispatch();
  const [poultryKey, setPolutryKey] = useState("");
  const [polutryData, setpolutryData] = useState("");
  const [enableHall, setEnableHall] = useState(true);
  const [numberOfhalls, setNumberOfHalls] = useState(1);
  const [numberOfhallSelected, setNumberOfHallSelected] = useState(null);
  const [openNotif, , selectedDate1, , selectedDate2] = useContext(AppContext);

  const formik2 = useFormik({
    initialValues: {
      userInfoCheck: "",
    },
    validationSchema: Yup.object({
      userInfoCheck: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی وارد کنید!"),
    }),
  });

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

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

  useEffect(() => {
    if (poultryKey) {
      if (numberOfhalls === 0) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "ابتدا برای این مرغداری جوجه ریزی ثبت کنید.",
          severity: "error",
        });
        dispatch(DRAWER({ right: false, bottom: false, content: null }));
      } else {
        setEnableHall(false);
      }
    }
  }, [poultryKey]);

  return (
    <>
      {!polutryData ? (
        <Grid>
          <Typography>جستجو کاربر</Typography>
          <Grid mt={SPACING.SMALL} display="flex" width={1}>
            <TextField
              fullWidth
              id="userInfoCheck"
              label="شماره موبایل یا کد ملی یا شناسه یکتا"
              variant="outlined"
              value={formik2.values.userInfoCheck}
              error={
                formik2.touched.userInfoCheck
                  ? Boolean(formik2.errors.userInfoCheck)
                  : null
              }
              onChange={formik2.handleChange}
              onBlur={formik2.handleBlur}
              helperText={
                formik2.touched.userInfoCheck &&
                Boolean(formik2.errors.userInfoCheck)
                  ? formik2.errors.userInfoCheck
                  : null
              }
            />

            <IconButton
              disabled={!formik2.isValid}
              aria-label="delete"
              color="primary"
              onClick={() => {
                dispatch(LOADING_START());
                dispatch(cityGetPoultryData(formik2.values.userInfoCheck)).then(
                  (r) => {
                    dispatch(LOADING_END());
                    if (r.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "کاربر یافت نشد",
                        severity: "error",
                      });
                    }
                    setpolutryData(r.payload.data);
                  }
                );
              }}
            >
              <SearchIcon />
            </IconButton>
          </Grid>
          <FormHelperText>شماره موبایل با صفر شروع می‌شود!</FormHelperText>
        </Grid>
      ) : (
        <Grid
          container
          gap={SPACING.SMALL}
          direction="column"
          flex="1"
          height="100%"
          justifyContent="space-between"
        >
          <Grid container direction="column" gap={SPACING.SMALL}>
            <Grid>
              <Autocomplete
                disablePortal
                id="hatching"
                options={
                  polutryData
                    ? polutryData.map((i) => ({
                        id: i.key,
                        label: i.unitName,
                        halls: i.numberOfHalls,
                      }))
                    : []
                }
                onChange={(event, value) => {
                  setPolutryKey(value.id);
                  setNumberOfHalls(value.halls);
                }}
                renderInput={(params) => (
                  <TextField {...params} label="محل پرورش" />
                )}
              />
            </Grid>
            <Grid>
              <Autocomplete
                disabled={enableHall}
                disablePortal
                options={[...Array(numberOfhalls)].map((e, i) => ({
                  label: "سالن شماره " + (i + 1),
                  id: i,
                }))}
                onChange={(event, value) => {
                  setNumberOfHallSelected(value.id + 1);
                }}
                renderInput={(params) => (
                  <TextField {...params} label="سالن را انتخاب کنید" />
                )}
              />
            </Grid>
            <NumberInput
              allowLeadingZeros
              thousandSeparator=","
              id="quantity"
              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
              }
              label="تعداد"
              variant="outlined"
            />
            <DatePicker
              label="تاریخ جوجه ریزی"
              id="hatchingDate"
              renderInput={(params) => <TextField {...params} />}
              value={formik.values.hatchingDate}
              error={
                formik.touched.hatchingDate
                  ? Boolean(formik.errors.hatchingDate)
                  : null
              }
              onChange={(e) => {
                formik.setFieldValue(
                  "hatchingDate",
                  moment(e).format("YYYY-MM-DD hh:mm:ss")
                );
              }}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.hatchingDate &&
                Boolean(formik.errors.hatchingDate)
                  ? formik.errors.hatchingDate
                  : null
              }
            />
            <FormControl fullWidth>
              <InputLabel id="demo-simple-select-label">نژاد مرغ</InputLabel>
              <Select
                labelId="demo-simple-select-label"
                id="race"
                label="نژاد مرغ"
                value={formik.values.race}
                error={formik.touched.race ? Boolean(formik.errors.race) : null}
                onChange={(e) => {
                  formik.setFieldValue("race", e.target.value);
                }}
                onBlur={formik.handleBlur}
              >
                <MenuItem value={"آرین"}>آرین</MenuItem>
                <MenuItem value={"راس"}>راس</MenuItem>
                <MenuItem value={"آربراکرز (آپلاس)"}>آربراکرز (آپلاس)</MenuItem>
                <MenuItem value={"کاب"}>کاب</MenuItem>
                <MenuItem value={"هوبارد"}>هوبارد</MenuItem>
                <MenuItem value={"ترکیبی"}>ترکیبی</MenuItem>
                <MenuItem value={"وارداتی"}>وارداتی</MenuItem>
              </Select>
              <FormHelperText>
                {formik.touched.race && Boolean(formik.errors.race)
                  ? formik.errors.race
                  : null}
              </FormHelperText>
            </FormControl>
          </Grid>

          <Grid>
            <Button
              disabled={
                formik.isValid && poultryKey.length && numberOfhallSelected
                  ? false
                  : true
              }
              fullWidth
              variant="contained"
              onClick={() => {
                dispatch(LOADING_START());
                dispatch(
                  avicultureNewHatching({
                    role: getRoleFromUrl(),
                    key: poultryKey,
                    quantity: formik.values.quantity,
                    date: formik.values.hatchingDate,
                    chicken_breed: formik.values.race,
                    hall: numberOfhallSelected,
                  })
                ).then((r) => {
                  dispatch(reloadHatchings());
                  dispatch(cityGetHatchings({ selectedDate1, selectedDate2 }));
                  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(
                      DRAWER({ right: false, bottom: false, content: null })
                    );
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                  dispatch(LOADING_END());
                });
              }}
            >
              ثبت اطلاعات
            </Button>
          </Grid>
        </Grid>
      )}
    </>
  );
};
