import React, { useEffect, useState } from "react";
import style from "./reviews.module.css";
import { useRouter } from "next/router";
import { Star, StarOutline, Stars } from "@mui/icons-material";
import { customerApi } from "@/api/api";
import Pagination from "@/components/utils/pagination";
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 EditReview from "./editReview";

const Reviews = (props) => {
  const [data, setData] = useState({ data: [], review: null });
  const [page, setPage] = useState(1);
  const [loader, setLoader] = useState(true);
  const account = useSelector((state) => state.accountStore);
  const [submitLoader, setSubmitLoader] = 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 router = useRouter();

  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
      .post("/review", { ...reviewData })
      .then((res) => {
        if (res.data.success === true) {
          createNotification("success", "Review Submited Successfully");
          loadData();
        } else {
          createNotification("error", "Failed To Add");
        }
        setSubmitLoader(false);
      })
      .catch((err) => {
        createNotification("error", "Something went wrong");
        setSubmitLoader(false);
        console.log(err);
      });
  };
  const loadData = async () => {
    setLoader(true);
    const params = JSON.stringify({
      product_id: props.product_id,
    });
    await customerApi
      .get("/reviews?limit=10&page=" + page + "&params=" + params)
      .then((res) => {
        console.log("Response: ", res);
        if (res.data.result) {
          setData(res.data.result);
        }
        setLoader(false);
      })
      .then((err) => {
        console.log("err");
        setLoader(false);
      });
  };
  useEffect(() => {
    loadData();
  }, [page]);
  return (
    <React.Fragment>
      <div className={props.className}>
        <h2 className={`${style.heading}`}>
          Customer Reviews{" "}
        </h2>

        {loader && <Loader className={style.loader} />}
        {!loader ? (
          <>
            {account.loggedIn && !data.review ? (
              <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}
                    />
                  </div>
                  <div className={style.button_section}>
                    {submitLoader && (
                      <div className={`secondary-btn`}>
                        <Loader className={style.submitLoader} />
                      </div>
                    )}
                    {!submitLoader && (
                      <button type="submit" className={`secondary-btn`}>
                        Submit
                      </button>
                    )}
                  </div>
                </div>
              </form>
            ) : (
              <>
                {account.loggedIn && data.review ? (
                  <EditReview loadData={() => loadData()} data={data.review} />
                ) : (
                  data.data.length <= 0 && (
                    <p className={style.no_reviews}>
                      No Reviews, <b>Login</b> to add reviews
                    </p>
                  )
                )}
              </>
            )}
            {data.data.map((item, index) => (
              <div className={style.review_section} key={index}>
                <div className={style.customer_name}>{item.user_name}</div>
                <div className={style.rating}>
                  {[...Array(item.rating)].map(() => (
                    <>
                      <Star />
                    </>
                  ))}
                </div>
                <div className={style.date}>
                  {moment(item.created_at).format("MMM Do YYYY")}
                </div>
                <div className={style.message}>{item.message}</div>
              </div>
            ))}
            {data.pageCount > 1 && (
              <Pagination
                totalData={data.total}
                totalDataPerPage={10}
                totalNumberToDisplay={5}
                page={page}
                getPage={(value) => setPage(value)}
              />
            )}
          </>
        ) : (
          !loader && <p className={style.no_reviews}>No Reviews</p>
        )}
      </div>
    </React.Fragment>
  );
};

export default Reviews;
