import { Box, Button, Divider, InputLabel, TextField } from "@mui/material";
import { useFormik } from "formik";
import * as React from "react";
import { useTheme } from "@mui/material/styles";
import OutlinedInput from "@mui/material/OutlinedInput";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";
import Chip from "@mui/material/Chip";

import { useDispatch, useSelector } from "react-redux";
import { provinceSendMessage } from "../../services/province-send-message";
import { useContext } from "react";
import { Yup } from "../../../../lib/yup/yup";
import { fixBase64 } from "../../../../utils/toBase64";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../../contexts/AppContext";
import { useEffect } from "react";
import { AutocompleteSelect } from "../../../../components/autocomplete-select/AutocompleteSelect";
import { getEnRoleFromFa } from "../../../../utils/getEnRoleFromFa";
// import { useState } from "react";

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

const names = ["شهرستان", "دامپزشک", "راننده", "مرغدار", "کشتارگاه", "مالی"];

function getStyles(name, personName, theme) {
  return {
    fontWeight:
      personName.indexOf(name) === -1
        ? theme.typography.fontWeightRegular
        : theme.typography.fontWeightMedium,
  };
}

const ProvinceSubmitMessage = () => {
  const [usersList, setUsersList] = React.useState([]);
  const { provinceUsers } = useSelector((state) => state.provinceSlice);

  useEffect(() => {
    setUsersList(
      provinceUsers.map((user) => {
        const userName = user.profile.fullname
          ? user.profile.fullname
          : `${user.profile.firstName} ${user.profile.lastName}`;
        return {
          id: user.profile.key,
          title: `${userName}`,
        };
      })
    );
  }, []);

  const formik = useFormik({
    initialValues: {
      description: "",
      linkText: "",
      heading: "",
      link: "",
      usersList: [],
    },
    validationSchema: Yup.object({
      description: Yup.string()
        .required("لطفا پیغام خود را بنویسید!")
        .typeError("لطفا فیلد را پر کنید!"),
      heading: Yup.string()
        .required("لطفا عنوان پیغام خود را بنویسید!")
        .typeError("لطفا فیلد را پر کنید!"),
      link: Yup.string().typeError("لطفا فیلد را پر کنید!"),
      linkText: Yup.string().typeError("لطفا فیلد را پر کنید!"),
    }),
  });

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

  const theme = useTheme();
  const [personName, setPersonName] = React.useState([]);
  //   const [setPersonNameKey] = useState("");

  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const [profileImages, setProfileImages] = React.useState([]);
  const [imagesData, setImagesData] = React.useState([]);

  const imagesHandler = (imageList, addUpdateIndex) => {
    setImagesData(imageList.map((img) => fixBase64(img.data_url)));
    setProfileImages(imageList);
  };

  const handleChange = (event) => {
    const {
      target: { value },
    } = event;
    setPersonName(typeof value === "string" ? value.split(",") : value);

    // const roles = [
    //   "",
    //   "Poultry",
    //   "VetFarm",
    //   "Driver",
    //   "KillHouse",
    //   "ProvinceFinancial",
    // ];
  };

  return (
    <>
      <Grid justifyContent="center">
        <Grid
          container
          justifyContent="center"
          xs={12}
          sm={12}
          md={8}
          lg={8}
          gap={SPACING.SMALL}
          direction="column"
        >
          <Grid>
            <TextField
              fullWidth
              id="heading"
              label="عنوان"
              variant="outlined"
              value={formik.values.heading}
              error={
                formik.touched.heading ? Boolean(formik.errors.heading) : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.heading && Boolean(formik.errors.heading)
                  ? formik.errors.heading
                  : null
              }
            />
          </Grid>
          <Grid justifyContent="center">
            <TextField
              fullWidth
              id="description"
              label="توضیحات"
              multiline
              rows={5}
              variant="outlined"
              sx={{ width: "100%", height: "100%" }}
              value={formik.values.description}
              error={
                formik.touched.description
                  ? Boolean(formik.errors.description)
                  : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.description && Boolean(formik.errors.description)
                  ? formik.errors.description
                  : null
              }
            />
          </Grid>
          <Grid>
            <FormControl fullWidth>
              <InputLabel>ارسال پیام بر اساس نقش</InputLabel>
              <Select
                id="demo-multiple-chip"
                multiple
                value={personName}
                onChange={handleChange}
                input={
                  <OutlinedInput
                    label={"ارسال پیام بر اساس نقش"}
                    id="select-multiple-chip"
                    // label="Chip"
                  />
                }
                renderValue={(selected) => (
                  <Box sx={{ display: "flex", flexWrap: "wrap", gap: 0.5 }}>
                    {selected.map((value) => (
                      <Chip key={value} label={value} />
                    ))}
                  </Box>
                )}
                MenuProps={MenuProps}
              >
                {names.map((name) => {
                  return (
                    <MenuItem
                      key={name}
                      value={name}
                      label={name}
                      style={getStyles(name, personName, theme)}
                    >
                      {name}
                    </MenuItem>
                  );
                })}
              </Select>
            </FormControl>
          </Grid>

          <Grid>
            <FormControl fullWidth>
              <Grid>
                <AutocompleteSelect
                  options={usersList}
                  title={"انتخاب کاربر"}
                  onChange={(item) => {
                    const ids = item.map((item) => item.id);
                    formik.setFieldValue("usersList", ids);
                  }}
                />
              </Grid>
              {/* <Grid>
                <Autocomplete
                  disablePortal
                  id="province"
                  options={usersList}
                  onChange={(event, value) => {
                    formik.setFieldValue("usersList", value.id);
                  }}
                  renderInput={(params) => (
                    <TextField {...params} label="استان را انتخاب  کنید" />
                  )}
                />
              </Grid> */}
            </FormControl>
          </Grid>

          <Grid>
            <ImageUpload
              onChange={imagesHandler}
              images={profileImages}
              maxNumber={5}
              title={"تصاویر ضمیمه"}
            />
          </Grid>
          <Grid m={SPACING.SMALL}>
            <Divider>
              <Chip label="پیوند" />
            </Divider>
          </Grid>
          <Grid>
            <TextField
              fullWidth
              size="small"
              id="linkText"
              label="متن توضیح پیوند"
              variant="outlined"
              value={formik.values.linkText}
              error={
                formik.touched.linkText ? Boolean(formik.errors.linkText) : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.linkText && Boolean(formik.errors.linkText)
                  ? formik.errors.linkText
                  : null
              }
            />
          </Grid>
          <Grid>
            <TextField
              fullWidth
              size="small"
              id="link"
              label="لینک"
              variant="outlined"
              value={formik.values.link}
              error={formik.touched.link ? Boolean(formik.errors.link) : null}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.link && Boolean(formik.errors.link)
                  ? formik.errors.link
                  : null
              }
            />
          </Grid>

          <Grid mb={SPACING.SMALL}>
            <Button
              fullWidth
              disabled={!formik.isValid}
              size="large"
              variant="contained"
              onClick={() => {
                if (!personName.length) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "لطفا کاربر هدف را انتخاب کنید.",
                    severity: "error",
                  });
                } else {
                  dispatch(LOADING_START());
                  dispatch(
                    provinceSendMessage({
                      roles: personName.map((role) => getEnRoleFromFa(role)),
                      users: formik.values.usersList,
                      heading: formik.values.heading,
                      message: formik.values.description,
                      link_text: formik.values.linkText,
                      link: formik.values.link,
                      image: imagesData,
                    })
                  ).then((r) => {
                    if (r.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "مشکلی پیش آمده است",
                        severity: "error",
                      });
                    } else {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "پیغام با موفقیت فرستاده شد.",
                        severity: "success",
                      });
                    }
                  });
                  dispatch(LOADING_END());
                }
              }}
            >
              ارسال پیغام
            </Button>
          </Grid>
        </Grid>
      </Grid>
    </>
  );
};

export default ProvinceSubmitMessage;
