import React, { useState, useEffect, useContext } from "react";
import { GlobalContext } from "../context/Provider";
import henceforthApi from "../utils/henceforthApi";
import Swal from "sweetalert2";
import { ChipButton } from "../components/BootstrapCompo";
import { toast } from "react-toastify";
interface notList {
  _id: string;
  email: string;
}
interface notlistUser {
  _id: string;
  name: string;
}
interface notification {
  type: string;
  send_to: any;
  user_ids: any;
  list_user: Array<notlistUser>;
  find_user: Array<notList>;
  selectedUser: any;
  country_filter: string;
  user_type_filter: string;
}
const ReactQuill =
  typeof window === "object" ? require("react-quill") : () => false;
const ALL_USERS = "ALL_USERS";
const SELECTED_USERS = "SELECTED_USERS";
const EMAIL = "EMAIL";
const PUSH = "PUSH";
const COUNTRY_ALL = "All";
const COUNTRY_SELECTED = "Selected users";
const COUNTRY_US = "US";
const COUNTRY_CA = "CA";
const COUNTRY_NG = "NG";
const USER_TYPE_ALL = "All";
const USER_TYPE_NOT_VERIFY = "NOT_VERIFY";
const USER_TYPE_ACCEPTED = "ACCEPTED";
const Notification = () => {
  const { authState, authDispatch, setLoading } = useContext(GlobalContext);
  if (authState.access_token) {
    henceforthApi.setToken(authState.access_token);
  }
  const [description, setDesciption] = useState("");
  const [inputValue, setInputValue] = useState("");
  const [subject, setSubject] = useState("");
  const [state, setState] = useState({
    type: EMAIL,
    send_to: ALL_USERS,
    user_ids: [],
    list_user: [],
    find_user: [],
    selectedUser: new Map(),
    country_filter: COUNTRY_ALL,
    user_type_filter: USER_TYPE_ALL,
  } as notification);
  const radioHandler = (send_to: any, country_filter?: string) => {
    setState({
      ...state,
      send_to,
      country_filter: country_filter || state.country_filter,
    });
  };
  const radioHandlerType = (type: any) => {
    setState({
      ...state,
      type,
    });
    setDesciption("");
  };
  const radioHandlerCountry = (country_filter: string) => {
    // If "Selected users" is selected, set send_to to SELECTED_USERS and user_type_filter to All
    const send_to =
      country_filter === COUNTRY_SELECTED ? SELECTED_USERS : ALL_USERS;
    setState({
      ...state,
      country_filter,
      send_to,
      user_type_filter: country_filter === COUNTRY_SELECTED ? USER_TYPE_ALL : state.user_type_filter,
    });
  };
  const radioHandlerUserType = (user_type_filter: string) => {
    setState({
      ...state,
      user_type_filter,
    });
  };
  function handleSubmit(e: any) {
    e.preventDefault();
    if (!subject) {
      return toast.warn("Please enter subject");
    }
    const items = {
      type: state.type,
      send_to: state.send_to,
      user_ids: state.user_ids,
      subject: subject,
      message: description,
      language: "ENGLISH",
      country_filter: state.country_filter,
      user_type_filter: state.user_type_filter,
    };
    henceforthApi.Administrator.sendNotifications(items)
      .then((res: any) => {
        Swal.fire({
          title: "Notification Sent",
          text: res.message,
          icon: "success",
          confirmButtonText: "OK",
        });
        setDesciption("");
        setSubject("");
        setState({
          ...state,
          user_ids: [],
          list_user: [],
          country_filter: COUNTRY_ALL,
          user_type_filter: USER_TYPE_ALL,
          send_to: ALL_USERS,
          selectedUser: new Map(),
        });
      })
      .catch((err: any) => {
        Swal.fire({
          title: "Error!",
          text: err.response.body.error_description,
          icon: "error",
          confirmButtonText: "Cancel",
        });
      });
  }
  const handleFIlter = async (value: any) => {
    setInputValue(value);
    if (value) {
      try {
        let apiRes = await henceforthApi.Common.allUsers(value);
        setState({
          ...state,
          find_user: apiRes.data.data,
        });
      } catch (error: any) {
        setState({
          ...state,
          find_user: [],
        });
      }
    }
  };
  const onClickChip = (_id: string, name: string) => {
    const { selectedUser } = state;
    if (selectedUser.has(_id)) {
      selectedUser.delete(_id);
    } else {
      selectedUser.set(_id, name);
    }
    let rowDataId = [] as Array<string>;
    let rowData = [] as Array<{ _id: string; name: string }>;
    selectedUser.forEach((res: any, key: any) => {
      rowDataId.push(key);
      rowData.push({ _id: key, name: res });
    });
    setState({
      ...state,
      list_user: rowData,
      selectedUser,
      user_ids: rowDataId,
      find_user: [],
    });
    setInputValue("");
  };
  const onEditorStateChange = (e: any) => {
    setDesciption(e);
  };

  return (
    <div className="row animated fadeInRight">
      <div className="col-md-12">
        <div className="ibox">
          <div className="ibox-title">Notification</div>
          <div className="ibox-content">
            <form onSubmit={handleSubmit}>
              <div className="mb-4">
                <label className="mb-2 d-block">Select users by Country</label>
                <div className="d-flex align-items-center flex-wrap gap-3">
                  <div
                    onClick={(e: any) => radioHandlerCountry(COUNTRY_ALL)}
                    className="radio-btn-notif d-flex align-items-center"
                  >
                    <input
                      type="radio"
                      name="country"
                      className="me-2"
                      checked={state.country_filter === COUNTRY_ALL}
                      readOnly
                    />
                    <label htmlFor="all">All Users</label>
                  </div>
                  <div
                    onClick={(e: any) => radioHandlerCountry(COUNTRY_US)}
                    className="radio-btn-notif d-flex align-items-center"
                  >
                    <input
                      type="radio"
                      name="country"
                      className="me-2"
                      checked={state.country_filter === COUNTRY_US}
                      readOnly
                    />
                    <label htmlFor="us">United States</label>
                  </div>
                  <div
                    onClick={(e: any) => radioHandlerCountry(COUNTRY_CA)}
                    className="radio-btn-notif d-flex align-items-center"
                  >
                    <input
                      type="radio"
                      name="country"
                      className="me-2"
                      checked={state.country_filter === COUNTRY_CA}
                      readOnly
                    />
                    <label htmlFor="ca">Canada</label>
                  </div>
                  <div
                    onClick={(e: any) => radioHandlerCountry(COUNTRY_NG)}
                    className="radio-btn-notif d-flex align-items-center"
                  >
                    <input
                      type="radio"
                      name="country"
                      className="me-2"
                      checked={state.country_filter === COUNTRY_NG}
                      readOnly
                    />
                    <label htmlFor="ng">Nigeria</label>
                  </div>
                  <div
                    onClick={(e: any) => radioHandlerCountry(COUNTRY_SELECTED)}
                    className="radio-btn-notif d-flex align-items-center"
                  >
                    <input
                      type="radio"
                      name="country"
                      className="me-2"
                      checked={state.country_filter === COUNTRY_SELECTED}
                      readOnly
                    />
                    <label htmlFor="selected">Only Selected Users</label>
                  </div>
                </div>
                {state.country_filter !== COUNTRY_SELECTED && (
                  <div className="mb-4 mt-3">
                    <label className="mb-2 d-block">User Type Filter</label>
                    <div className="d-flex align-items-center">
                      <div
                        onClick={(e: any) => radioHandlerUserType(USER_TYPE_ALL)}
                        className="radio-btn-notif d-flex align-items-center me-3"
                      >
                        <input
                          type="radio"
                          name="user_type"
                          className="me-2"
                          checked={state.user_type_filter === USER_TYPE_ALL}
                          readOnly
                        />
                        <label htmlFor="user_type_all">All</label>
                      </div>
                      <div
                        onClick={(e: any) =>
                          radioHandlerUserType(USER_TYPE_NOT_VERIFY)
                        }
                        className="radio-btn-notif d-flex align-items-center me-3"
                      >
                        <input
                          type="radio"
                          name="user_type"
                          className="me-2"
                          checked={
                            state.user_type_filter === USER_TYPE_NOT_VERIFY
                          }
                          readOnly
                        />
                        <label htmlFor="user_type_not_verify">NOT VERIFIED</label>
                      </div>
                      <div
                        onClick={(e: any) =>
                          radioHandlerUserType(USER_TYPE_ACCEPTED)
                        }
                        className="radio-btn-notif d-flex align-items-center"
                      >
                        <input
                          type="radio"
                          name="user_type"
                          className="me-2"
                          checked={state.user_type_filter === USER_TYPE_ACCEPTED}
                          readOnly
                        />
                        <label htmlFor="user_type_accepted">ACCEPTED</label>
                      </div>
                    </div>
                  </div>
                )}
                {state.country_filter === COUNTRY_SELECTED ? (
                  <>
                    <div className="mt-3">
                      <input
                        type="text"
                        className="form-control"
                        placeholder="Select user by email"
                        value={inputValue}
                        onChange={(e: any) => handleFIlter(e.target.value)}
                      />
                      <ul className="list-group">
                        {state.find_user.map((res: any) => {
                          return (
                            <li
                              className="list-group-item"
                              onClick={() =>
                                onClickChip(res._id, `${res.email}`)
                              }
                            >
                              {res.email}{" "}
                            </li>
                          );
                        })}
                      </ul>
                    </div>
                    {state.list_user.length ? (
                      <>
                        <hr />
                        <div className="form-group">
                          <label className="mb-2">Selected User</label>
                          <div className=" d-flex flex-wrap gap-1">
                            {state.list_user.map((res: any) => {
                              return (
                                <ChipButton
                                  key={res._id}
                                  _id={res._id}
                                  name={res.name}
                                  onClick={onClickChip}
                                />
                              );
                            })}
                          </div>
                        </div>
                      </>
                    ) : (
                      ""
                    )}
                  </>
                ) : (
                  ""
                )}
              </div>
              <div className="form-group">
                <label className="mb-2">Subject</label>
                <input
                  name="subject"
                  type="text"
                  className="form-control text-dark"
                  value={subject}
                  onChange={(e: any) => setSubject(e.target.value)}
                />
              </div>
              <div className="mb-4">
                {/* <label className="mb-2 d-block">Select users by type</label> */}
                <div className="d-flex align-items-center">
                  <div
                    onClick={(e: any) => radioHandlerType(EMAIL)}
                    className="radio-btn-notif d-flex align-items-center me-3"
                  >
                    <input
                      type="radio"
                      name="type"
                      className="me-2"
                      checked={state.type === EMAIL}
                      readOnly
                    />
                    <label htmlFor="email">Email</label>
                  </div>
                  <div
                    onClick={(e: any) => radioHandlerType(PUSH)}
                    className=" radio-btn-notif d-flex align-items-center"
                  >
                    <input
                      type="radio"
                      name="type"
                      className="me-2"
                      checked={state.type === PUSH}
                      readOnly
                    />
                    <label htmlFor="push">Push</label>
                  </div>
                </div>
              </div>

              {state.type === EMAIL ? (
                <div
                  style={{
                    border: "1px solid rgba(0,0,0,.2)",
                    paddingBottom: "20px",
                    background: "white",
                    marginBottom: "20px",
                    maxHeight: "200px",
                  }}
                >
                  <ReactQuill
                    theme="snow"
                    className="text-dark"
                    onChange={(e: any) => onEditorStateChange(e)}
                    placeholder={`Write your content`}
                    value={description}
                  />
                </div>
              ) : (
                <textarea
                  className="w-100 text-dark"
                  onChange={(e: any) => setDesciption(e.target.value)}
                  value={description}
                ></textarea>
              )}
              <div className="form-group">
                <button
                  type="submit"
                  className="btn dashboard-button btn-color"
                  disabled={
                    state.country_filter === COUNTRY_SELECTED &&
                    state.user_ids.length === 0
                  }
                >
                  Submit
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Notification;
