import React, { useEffect, useState } from "react";
import style from "./editReview.module.css";
import { Star, StarOutline, Stars } from "@mui/icons-material";
import { customerApi } from "@/api/api";
import Loader from "@/components/utils/loader";
import moment from "moment";
import InputText from "@/components/utils/inputText";
import { createNotification } from "@/customHook/useNotification";
import { useSelector } from "react-redux";
import ConfirmBox from "@/components/utils/confirmBox";
import { confirmAlert } from "react-confirm-alert";

const EditReview = (props) => {
  const account = useSelector((state) => state.accountStore);
  const [submitLoader, setSubmitLoader] = useState(false);
  const [edit, setEdit] = useState(false);
  const [deleteBtnLoader, setDeletebtnLoader] = useState(false);
  const [reviewData, setReviewData] = useState({
    rating: 0,
    message: "",
    product_id: props.product_id,
    product_code: props.product_code,
  });

  useEffect(() => {
    console.log("reviewData:", reviewData);
  }, [reviewData]);

  const submitHandler = async (e) => {
    e.preventDefault();
    if (!reviewData.rating || reviewData.rating <= 0) {
      createNotification("error", "Select the rating stars");
      return;
    }
    if (
      !reviewData.message ||
      !reviewData.product_id ||
      !reviewData.product_code
    ) {
      createNotification("error", "Complete required field");
      return;
    }
    setSubmitLoader(true);
    await customerApi
      .put("/review", { ...reviewData })
      .then((res) => {
        if (res.data.success === true) {
          createNotification("success", "Review Edited Successfully");
          props.loadData();
        } else {
          createNotification("error", "Failed To Edit");
        }
        setSubmitLoader(false);
      })
      .catch((err) => {
        createNotification("error", "Something went wrong");
        setSubmitLoader(false);
        console.log(err);
      });
  };

  const onDeleteReview = async (id) => {
    setDeletebtnLoader(true);
    await customerApi
      .delete("/review", { data: { _id: id } })
      .then((res) => {
        if (res.data.success === true) {
          createNotification("success", "Review Deleted");
          props.loadData();
        } else {
          createNotification("error", "Failed To Delete");
        }
        setDeletebtnLoader(false);
      })
      .catch((err) => {
        createNotification("error", "Something went wrong");
        setDeletebtnLoader(false);
        console.log(err);
      });
  };

  const confirmDelete = (id) => {
    confirmAlert({
      customUI: ({ onClose }) => {
        return (
          <ConfirmBox onClose={onClose} onConfirm={() => onDeleteReview(id)} />
        );
      },
    });
  };

  useEffect(() => {
    console.log("props.re", props.data);
    setReviewData(props.data);
  }, [props.data]);
  return (
    <React.Fragment>
      <div className={props.className}>
        {!edit && (
          <div className={style.review_section}>
            <div className={style.customer_name}>{props.data.user_name}</div>
            <div className={style.rating}>
              {[...Array(props.data.rating)].map(() => (
                <>
                  <Star />
                </>
              ))}
            </div>
            <div className={style.date}>
              {moment(props.data.created_at).format("MMM Do YYYY")}
            </div>
            <div className={style.message}>{props.data.message}</div>
            {submitLoader && (
              <div className={`secondary-btn`}>
                <Loader className={style.submitLoader} />
              </div>
            )}
            <div className={style.button_section}>
              <button
                type="submit"
                className={`secondary-btn`}
                onClick={() => setEdit(true)}
              >
                Edit
              </button>
              {!deleteBtnLoader ? (
                <button
                  type="submit"
                  className={`secondary-btn`}
                  onClick={() => confirmDelete(props.data._id)}
                >
                  Delete
                </button>
              ) : (
                <div className={`secondary-btn`}>
                  <Loader className={style.submitLoader} />
                </div>
              )}
            </div>
          </div>
        )}
        {account.loggedIn && edit && (
          <form onSubmit={submitHandler}>
            <div className={style.add_review_section}>
              <div className={style.rating_section}>
                <p>Select Rating :</p>
                {[...Array(5)].map((item, index) => (
                  <div
                    key={index}
                    onClick={() =>
                      setReviewData((prev) => {
                        let newObject = { ...prev };
                        newObject.rating = index + 1;
                        return newObject;
                      })
                    }
                    className={`${
                      reviewData.rating - 1 >= index ? style.selected : ""
                    }`}
                  >
                    {reviewData.rating - 1 >= index ? (
                      <Star />
                    ) : (
                      <StarOutline />
                    )}
                  </div>
                ))}
              </div>
              <div className={style.message_section}>
                <InputText
                  inputType="textarea"
                  placeholder="Enter review here..."
                  getValue={(value) => {
                    setReviewData((prev) => {
                      let newObject = { ...prev };
                      newObject.message = value;
                      return newObject;
                    });
                  }}
                  rows={5}
                  required={true}
                  value={reviewData.message}
                />
              </div>
              <div className={style.edit_button_section}>
                {submitLoader && (
                  <div className={`secondary-btn`}>
                    <Loader className={style.submitLoader} />
                  </div>
                )}
                {!submitLoader && (
                  <>
                    <button type="submit" className={`secondary-btn`}>
                      Submit
                    </button>
                    <button
                      type="button"
                      onClick={() => setEdit(false)}
                      className={`secondary-btn`}
                    >
                      Cancel
                    </button>
                  </>
                )}
              </div>
            </div>
          </form>
        )}
      </div>
    </React.Fragment>
  );
};

export default EditReview;
