import { useContext, useEffect, useState } from "react";
import useUserProfile from "../../../authentication/hooks/useUserProfile";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { fixBase64 } from "../../../../utils/toBase64";
import { Grid } from "../../../../components/grid/Grid";
import {
  Autocomplete,
  Button,
  Checkbox,
  FormControl,
  FormControlLabel,
  InputLabel,
  MenuItem,
  // Paper,
  Select,
  TextField,
  Typography,
  Chip,
  Box,
  Stack,
} from "@mui/material";
// import LaunchIcon from "@mui/icons-material/Launch";
// import SettingsSuggestIcon from "@mui/icons-material/SettingsSuggest";
// import MarkAsUnreadIcon from "@mui/icons-material/MarkAsUnread";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { useDispatch } from "react-redux";
import {
  getTicketPermission,
  getTicketUsersFromRole,
} from "../../services/get-ticket-permission";
import { AppContext } from "../../../../contexts/AppContext";
import { CreateTicketService } from "../../services/create-ticket";
import { sendResponseTicketService } from "../../services/send-response";
import { useNavigate } from "react-router-dom";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import DeleteIcon from "@mui/icons-material/Delete";
// import MoreHorizIcon from "@mui/icons-material/MoreHoriz";
import { styled } from "@mui/material/styles";

const VisuallyHiddenInput = styled("input")({
  clip: "rect(0 0 0 0)",
  clipPath: "inset(50%)",
  height: 1,
  overflow: "hidden",
  position: "absolute",
  bottom: 0,
  left: 0,
  whiteSpace: "nowrap",
  width: 1,
});

export const CreateTicket = ({ id, getMessages, fetchMessages }) => {
  // const ticketTypes = [
  //   {
  //     title: "درخواست از مدیر",
  //     icon: <LaunchIcon fontSize="40%" />,
  //     color: "#797979",
  //   },
  //   {
  //     title: "مشکلات فنی",
  //     icon: <SettingsSuggestIcon fontSize="40%" />,
  //     color: "#797979",
  //   },
  //   {
  //     title: "پیشنهاد و انتقاد",
  //     icon: <MarkAsUnreadIcon fontSize="40%" />,
  //     color: "#797979",
  //   },
  // ];

  const isAdmin = () => {
    if (
      selectedRole === "CityOperator" ||
      selectedRole === "ProvinceOperator" ||
      selectedRole === "AdminX" ||
      selectedRole === "Supporter" ||
      selectedRole === "SuperAdmin"
    ) {
      return true;
    } else {
      return false;
    }
  };
  const [role] = useUserProfile();
  const [selectedRole, setSelectedRole] = useState(role[0]);
  const [value, setValue] = useState(isAdmin() ? "toRole" : "toUser");
  const [openNotif] = useContext(AppContext);
  const navigate = useNavigate();

  // const handleChangeRadioButton = (event) => {
  //   formik.setFieldValue("roles", []);
  //   setValue(event.target.value);
  // };

  const dispatch = useDispatch();
  const handleRoleChange = (event) => {
    setSelectedRole(event.target.value);
  };

  const [isChecked, setChecked] = useState(false);

  const handleCheckboxChange = () => {
    setChecked(!isChecked);
  };

  const handleFileUpload = (event) => {
    const file = event.target.files[0];
    if (file) {
      formik.setFieldValue("uploadedFile", file);
    }
  };

  const handleDeleteFile = () => {
    formik.setFieldValue("uploadedFile", null);
  };

  const formik = useFormik({
    initialValues: {
      title: "",
      text: "",
      users: [],
      roles: [],
      image: "",
      uploadedFile: null,
    },
    validationSchema: Yup.object({
      title: Yup.string().required("عنوان تیکت ضروری است"),
      text: Yup.string().required("متن تیکت ضروری است"),
    }),
    onSubmit: (values) => {
      // console.log(values);
    },
  });

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

  useEffect(() => {
    if (!isAdmin()) {
      setValue("toUser");
    }
  }, [value, selectedRole]);

  const [profileImages, setProfileImages] = useState([]);

  const factorPaymentHandler = (imageList, addUpdateIndex) => {
    if (imageList[0]) {
      formik.setFieldValue("image", fixBase64(imageList[0]?.data_url));
    }
    setProfileImages(imageList);
  };

  const [permissionList, setPermissionList] = useState([]);
  const [users, setUsers] = useState([]);

  useEffect(() => {
    dispatch(getTicketPermission({ role: selectedRole })).then((r) => {
      setPermissionList(r.payload.data);
    });
  }, [selectedRole]);
  useEffect(() => {
    if (formik.values.roles.length && value === "toUser") {
      dispatch(getTicketUsersFromRole({ role: formik.values.roles })).then(
        (r) => {
          setUsers(r.payload.data);
        }
      );
    } else {
      setUsers([]);
    }
  }, [formik.values.roles, value]);

  const handleCheckboxChangeToRole = (event) => {
    if (event.target.checked) {
      setValue("toRole");
      formik.setFieldValue("users", []);
      formik.setFieldValue("roles", []);
    }
  };

  const handleCheckboxChangeToUser = (event) => {
    if (event.target.checked) {
      setValue("toUser");
      formik.setFieldValue("roles", []);
      formik.setFieldValue("users", []);
    }
  };

  return (
    <Grid
      container
      alignItems="center"
      justifyContent="center"
      gap={2}
      width="100%"
    >
      {/* <Grid item xs={12} container justifyContent="center">
        <Box
          display="flex"
          justifyContent="center"
          gap={2}
          mb={3}
          sx={{
            "& > *": { width: "100px", height: "120px", flex: "0 0 auto" },
          }}
        >
          {ticketTypes.map((item) => (
            <Paper
              key={item.title}
              sx={{
                p: 3,
                textAlign: "center",
                cursor: "pointer",

                borderRadius: 2,
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                justifyContent: "center",

                minHeight: 150,
                transition: "all 0.3s ease",
                "&:hover": {
                  transform: "translateY(-5px)",
                  boxShadow: 4,
                },
              }}
            >
              <Box
                sx={{
                  color: item.color,
                  mb: 2,
                  fontSize: "2.5rem",
                }}
              >
                {item.icon}
              </Box>
              <Typography
                variant="h6"
                sx={{ fontWeight: "medium", fontSize: "12px" }}
              >
                {item.title}
              </Typography>
            </Paper>
          ))}
        </Box>
      </Grid> */}
      {isNaN(id) && (
        <Grid container justifyContent="center" xs={12}>
          <Grid item xs={12} container justifyContent="center">
            <Stack direction="row" spacing={4}>
              <FormControlLabel
                control={
                  <Checkbox
                    checked={value === "toRole"}
                    onChange={handleCheckboxChangeToRole}
                    disabled={!isAdmin()}
                  />
                }
                label="ارسال به نقش"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    checked={value === "toUser"}
                    onChange={handleCheckboxChangeToUser}
                  />
                }
                label="ارسال به اشخاص"
              />
            </Stack>
          </Grid>
          <Grid item xs={12} container justifyContent="center">
            {permissionList?.roles?.length &&
            (value === "toRole" ? isAdmin() : true) ? (
              <Grid item xs={12}>
                <FormControl fullWidth>
                  <InputLabel id="role-select-label">انتخاب نقش</InputLabel>
                  <Select
                    multiple={value !== "toUser"}
                    labelId="role-select-label"
                    value={formik.values.roles}
                    onChange={(event) => {
                      formik.setFieldValue("roles", event.target.value);
                    }}
                    fullWidth
                  >
                    {permissionList?.roles.map((roleItem, i) => (
                      <MenuItem key={i} value={roleItem}>
                        {getFaUserRole(roleItem)}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>
            ) : (
              <Typography variant="body1" color="error">
                نقش انتخابی اجازه ارسال تیکت ندارد!
              </Typography>
            )}
          </Grid>
          {value === "toUser" && (
            <>
              {users?.length ? (
                <Grid item xs={12} mt={2} v>
                  <Autocomplete
                    multiple
                    id="tags-standard"
                    options={users}
                    getOptionLabel={(option) => option.fullname}
                    onChange={(event, value) => {
                      formik.setFieldValue("users", value);
                    }}
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        variant="outlined"
                        label="انتخاب کاربر"
                      />
                    )}
                  />
                </Grid>
              ) : (
                <Typography color="error" variant="body2">
                  موردی یافت نشد!
                </Typography>
              )}
            </>
          )}
        </Grid>
      )}
      {role.length > 1 && isNaN(id) && (
        <Grid item xs={12} container justifyContent="center">
          <FormControl fullWidth>
            <InputLabel id="role-select-label">انتخاب نقش</InputLabel>
            <Select
              labelId="role-select-label"
              value={selectedRole}
              onChange={handleRoleChange}
            >
              {role.map((roleItem, i) => (
                <MenuItem key={i} value={roleItem}>
                  {getFaUserRole(roleItem)}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Grid>
      )}

      {isNaN(id) && (
        <Grid item xs={12} container justifyContent="center">
          <TextField
            id="title"
            name="title"
            label="موضوع"
            value={formik.values.title}
            onChange={formik.handleChange}
            error={formik.touched.title && Boolean(formik.errors.title)}
            helperText={formik.touched.title && formik.errors.title}
          />
        </Grid>
      )}
      <Grid item xs={12} container justifyContent="center">
        <TextField
          fullWidth
          id="text"
          name="text"
          label="پیام خود را وارد کنید"
          multiline
          rows={4}
          value={formik.values.text}
          onChange={formik.handleChange}
          error={formik.touched.text && Boolean(formik.errors.text)}
          helperText={formik.touched.text && formik.errors.text}
        />
      </Grid>

      <Grid item xs={12} mt={2}>
        <Button
          component="label"
          variant="outlined"
          startIcon={<CloudUploadIcon />}
          sx={{ mb: 1 }}
        >
          پیوست فایل
          <VisuallyHiddenInput type="file" onChange={handleFileUpload} />
        </Button>
        {formik.values.uploadedFile && (
          <Box display="flex" alignItems="center" mt={1}>
            <Chip
              label={formik.values.uploadedFile.name}
              onDelete={handleDeleteFile}
              deleteIcon={<DeleteIcon />}
              variant="outlined"
            />
            <Typography variant="caption" ml={1}>
              حجم: {(formik.values.uploadedFile.size / 1024 / 1024).toFixed(2)}{" "}
              MB
            </Typography>
          </Box>
        )}
        {formik.values.uploadedFile?.size > 5 * 1024 * 1024 && (
          <Typography color="error" variant="body2">
            حداکثر حجم مجاز جهت ارسال فایل 5 مگابایت است!
          </Typography>
        )}
      </Grid>

      {isAdmin() && isNaN(id) && (
        <Grid container xs={12}>
          <FormControlLabel
            control={
              <Checkbox
                disabled={
                  value === "toUser" &&
                  Array.isArray(formik.values.users) &&
                  formik.values.users.length === 1
                }
                size="small"
                checked={isChecked}
                onChange={handleCheckboxChange}
              />
            }
            label="فقط خواندنی"
          />
        </Grid>
      )}

      <Grid
        container
        justifyContent="center"
        style={{ marginTop: "16px" }}
        gap={2}
      >
        <ImageUpload
          onChange={factorPaymentHandler}
          images={profileImages}
          maxNumber={1}
          title={"ارسال تصویر"}
        />
      </Grid>

      <Button
        disabled={
          formik.values.uploadedFile?.size > 5 * 1024 * 1024 ||
          (!isNaN(id)
            ? !formik.values.text
            : value === "toUser"
            ? !formik.isValid || !formik.values.users.length
            : !formik.isValid || !formik.values.roles.length)
        }
        onClick={() => {
          if (!isNaN(id)) {
            const formData = new FormData();
            formData.append("message", formik.values.text);
            formData.append("sender", isAdmin() ? "user" : "admin");
            formData.append("send_message", false);
            formData.append("ticket", id);
            if (formik.values.image) {
              formData.append("image", formik.values.image);
            }

            if (formik.values.uploadedFile) {
              formData.append("file", formik.values.uploadedFile);
            }

            dispatch(sendResponseTicketService(formData)).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.data.result,
                  severity: "error",
                });
              } else {
                formik.resetForm();
                setProfileImages([]);
                fetchMessages();
                getMessages();
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          } else {
            if (value === "toUser") {
              dispatch(
                CreateTicketService({
                  type_ticket:
                    formik.values.users?.length === 1 ? "single" : "public",
                  to_user: formik.values.users.map((item) => {
                    return item?.key;
                  }),
                  image: formik.values.image ? formik.values.image : null,
                  title: formik.values.title,
                  sender: isAdmin() ? "user" : "admin",
                  message: formik.values.text,
                  read_only:
                    formik.values.users?.length === 1 ? false : isChecked,
                  role: selectedRole,
                })
              ).then((r) => {
                if (r.payload.error) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: r.payload.data.result,
                    severity: "error",
                  });
                } else {
                  formik.resetForm();
                  navigate(-1);
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "عملیات با موفقیت انجام شد.",
                    severity: "success",
                  });
                }
              });
            } else {
              dispatch(
                CreateTicketService({
                  type_ticket: "public",
                  to_role: formik.values.roles,
                  image: formik.values.image ? formik.values.image : null,
                  title: formik.values.title,
                  sender: isAdmin() ? "user" : "admin",
                  message: formik.values.text,
                  read_only: isChecked,
                  role: selectedRole,
                })
              ).then((r) => {
                if (r.payload.error) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: r.payload.error,
                    severity: "error",
                  });
                } else {
                  formik.resetForm();
                  navigate(-1);
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "عملیات با موفقیت انجام شد.",
                    severity: "success",
                  });
                }
              });
            }
          }
        }}
        color="primary"
        variant="contained"
        fullWidth
        type="submit"
        style={{ marginTop: "16px" }}
      >
        ارسال
      </Button>
    </Grid>
  );
};
