import {
  Autocomplete,
  Button,
  // Checkbox,
  Card,
  CardContent,
  CardActions,
  FormControl,
  IconButton,
  InputLabel,
  ListItemText,
  MenuItem,
  OutlinedInput,
  Select,
  TextField,
  Typography,
  Box,
} from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import React, { useContext, useEffect, useRef, useState } from "react";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import SearchIcon from "@mui/icons-material/Search";
import DeleteIcon from "@mui/icons-material/Delete";

import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useDispatch } from "react-redux";
import { vetFarmNewFarm } from "../../services/vet-farm-new-farm";
import { getVetFarmData } from "../../services/vet-farm-get-farm-data";
import { getVetFarms } from "../../services/vet-farm-get-farms";
import { AppContext } from "../../../../contexts/AppContext";
import { inspectorDeleteVetFarmService } from "../../../inspector/services/inspector-delete-vet-farm";

export const VetFarmSubmitFarmInfoForm = ({
  vetFarmKey,
  item,
  updateTable,
}) => {
  const [isExistPolutry, setIsExistPolutry] = useState(true);
  const [poultryKey, setPolutryKey] = useState("");
  const [polutryData, setpolutryData] = useState("");

  // const [numberOfhalls, setNumberOfHalls] = useState(1);
  const [numberOfHallsArray, setNumberOfHallsArray] = useState([]);
  const [registerVetHalls, setRegisterVetHalls] = useState([]);

  const [openNotif] = useContext(AppContext);

  const ITEM_HEIGHT = 48;
  const ITEM_PADDING_TOP = 8;
  const MenuProps = {
    PaperProps: {
      style: {
        maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
        width: 250,
      },
    },
  };

  const [hallName, setHallName] = React.useState([]);
  const [avicultureData, setAvicultureData] = React.useState([]);

  useEffect(() => {
    if (polutryData) {
      setAvicultureData(
        polutryData?.map((item) => ({
          id: item.key,
          label: item.unitName,
          halls: item.numberOfHalls,
          registerVetHalls: item.registerVetHalls,
        }))
      );
    }
  }, [polutryData]);

  const handleChange = (event) => {
    const {
      target: { value },
    } = event;

    setHallName(typeof value === "string" ? value.split(",") : value);
  };

  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      uniqueID: "",
      hatching: "",
    },
    validationSchema: Yup.object({
      uniqueID: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به صورت عددی وارد کنید!"),
      hatching: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی وارد کنید!"),
    }),
  });

  // useEffect(() => {
  //   if (formik.values.uniqueID) {
  //     dispatch(LOADING_START());
  //     // setNumberOfHalls();
  //     setNumberOfHallsArray([]);
  //     setHallName([]);
  //     dispatch(getVetFarmData(formik.values.uniqueID)).then((r) => {
  //       if (r.error) {
  //         dispatch(LOADING_END());
  //         openNotif({
  //           vertical: "top",
  //           horizontal: "center",
  //           msg: "مرغداری با این شناسه یافت نشد!",
  //           severity: "error",
  //         });
  //       }
  //       if (r.payload.data) {
  //         dispatch(LOADING_END());
  //         setIsExistPolutry(false);
  //         setpolutryData(r.payload.data);
  //       }
  //     });
  //   }
  // }, [formik.values.uniqueID]);

  // useEffect(() => {
  //   dispatch(avicultureGetHalls()).then((r) => {
  //     setNumberOfHalls(r.payload.data[0]?.poultry.numberOfHalls);
  //     if (r)
  //   });
  // }, [poultryKey]);

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

  const poultryRef = useRef();

  useEffect(() => {
    const el = poultryRef.current.querySelector(
      ".MuiAutocomplete-popupIndicator"
    );
    el.click();
  }, [avicultureData]);

  return (
    <Grid
      container
      gap={SPACING.SMALL}
      direction="column"
      flex="1"
      height="100%"
      justifyContent="space-between"
    >
      <Grid container direction="column" gap={SPACING.SMALL}>
        <Grid display="flex" width={1}>
          <TextField
            id="uniqueID"
            label="جستجو براساس شناسه یکتا یا کدملی فرد"
            variant="outlined"
            sx={{ width: "100%" }}
            value={formik.values.uniqueID}
            error={
              formik.touched.uniqueID ? Boolean(formik.errors.uniqueID) : null
            }
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.uniqueID && Boolean(formik.errors.uniqueID)
                ? formik.errors.uniqueID
                : null
            }
          />
          <IconButton
            disabled={!formik.values.uniqueID}
            aria-label="delete"
            color="primary"
            onClick={() => {
              if (formik.values.uniqueID) {
                dispatch(LOADING_START());
                // setNumberOfHalls();
                setNumberOfHallsArray([]);
                setHallName([]);
                dispatch(getVetFarmData(formik.values.uniqueID)).then((r) => {
                  if (r.error) {
                    dispatch(LOADING_END());
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "مرغداری با این شناسه یافت نشد!",
                      severity: "error",
                    });
                  }
                  if (r.payload.data) {
                    dispatch(LOADING_END());
                    setIsExistPolutry(false);
                    setpolutryData(r.payload.data);
                    poultryRef.current.focus();
                  }
                });
              }
            }}
          >
            <SearchIcon />
          </IconButton>
        </Grid>

        <Grid>
          <Autocomplete
            ref={poultryRef}
            disabled={isExistPolutry}
            disablePortal
            id="hatching"
            options={avicultureData}
            onChange={(event, value) => {
              setPolutryKey(value.id);
              // setNumberOfHalls(value.halls);
              setRegisterVetHalls(value.registerVetHalls);
              setHallName([]);
              setNumberOfHallsArray(new Array(value.halls).fill("*"));
            }}
            renderInput={(params) => (
              <TextField {...params} label="مرغداری را انتخاب  کنید" />
            )}
          />
        </Grid>

        <Grid>
          <FormControl>
            <InputLabel id="demo-multiple-checkbox-label">
              {numberOfHallsArray.length ? "انتخاب سالن" : "سالنی موجود نیست"}
            </InputLabel>
            <Select
              maxWidth="100%"
              disabled={!numberOfHallsArray.length}
              fullWidth
              labelId="demo-multiple-checkbox-label"
              id="demo-multiple-checkbox"
              multiple
              onChange={handleChange}
              value={hallName}
              input={<OutlinedInput label="انتخاب سالن" />}
              renderValue={(selected) => selected.join(", ")}
              MenuProps={MenuProps}
            >
              {numberOfHallsArray.map((name, i) => {
                const title = "سالن شماره " + (i + 1);
                const no = i + 1;
                return (
                  <MenuItem
                    key={i}
                    value={title}
                    disabled={registerVetHalls.includes(no)}
                  >
                    {/* <Checkbox checked={hallName.indexOf(name) > -1} /> */}
                    <ListItemText primary={title} />
                  </MenuItem>
                );
              })}
            </Select>
          </FormControl>
        </Grid>
      </Grid>
      <Grid mt={SPACING.SMALL}>
        <Button
          fullWidth
          variant="contained"
          disabled={!hallName.length}
          onClick={() => {
            dispatch(LOADING_START());
            dispatch(
              vetFarmNewFarm({
                poultry_key: poultryKey,
                halls: hallName.map((item) => item.split(" ")[2]),
                vet_key: vetFarmKey,
                // hall: numberOfhallSelected,
              })
            ).then((r) => {
              if (r.error) {
                dispatch(LOADING_END());
                if (r.error.message.includes("403")) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "قبلا این مرغداری و این سالن را ثبت کرده‌اید",
                    severity: "error",
                  });

                  dispatch(
                    DRAWER({ right: false, bottom: false, content: null })
                  );
                } else {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "مشکلی پیش آمده است!",
                    severity: "error",
                  });
                }
              } else {
                updateTable();
                dispatch(getVetFarms());
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });

                dispatch(
                  DRAWER({ right: false, bottom: false, content: null })
                );
                dispatch(LOADING_END());
              }
            });
          }}
        >
          ثبت اطلاعات
        </Button>
      </Grid>
      <Grid container direction="column" gap={SPACING.SMALL} mt={SPACING.SMALL}>
        <Grid>
          <Typography variant="body1">فارم های ثبت شده</Typography>
        </Grid>
        <Grid container direction="column" gap={SPACING.SMALL}>
          {item?.farms?.map((it, i) => {
            return (
              <Card
                key={i}
                sx={{
                  width: "100%",
                  transition: "all 0.3s ease-in-out",
                  "&:hover": {
                    transform: "translateY(-2px)",
                    boxShadow: 4,
                  },
                  borderLeft: "4px solid",
                  borderLeftColor: "primary.main",
                  borderRadius: 2,
                }}
              >
                <CardContent sx={{ pb: 1, "&:last-child": { pb: 1 } }}>
                  <Box
                    display="flex"
                    alignItems="center"
                    justifyContent="space-between"
                    gap={SPACING.SMALL}
                  >
                    <Box display="flex" alignItems="center" gap={1.5} flex={1}>
                      <Typography
                        variant="body1"
                        sx={{
                          fontWeight: 500,
                          color: "text.primary",
                          flex: 1,
                        }}
                      >
                        {it.poultryName}
                      </Typography>
                    </Box>
                    <CardActions sx={{ p: 0, m: 0 }}>
                      <Button
                        color="error"
                        variant="contained"
                        size="small"
                        startIcon={<DeleteIcon />}
                        onClick={() => {
                          dispatch(
                            inspectorDeleteVetFarmService({
                              vet_farm_key: it.vetFarmKey,
                            })
                          ).then((r) => {
                            if (r.payload.error) {
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: r.payload.error,
                                severity: "error",
                              });
                            } else {
                              updateTable();
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: "عملیات با موفقیت انجام شد.",
                                severity: "success",
                              });
                              dispatch(
                                DRAWER({
                                  right: false,
                                  bottom: false,
                                  content: null,
                                })
                              );
                            }
                          });
                        }}
                        sx={{
                          textTransform: "none",
                          borderRadius: 2,
                          px: 2,
                        }}
                      >
                        حذف
                      </Button>
                    </CardActions>
                  </Box>
                </CardContent>
              </Card>
            );
          })}
        </Grid>
      </Grid>
    </Grid>
  );
};
