import React, { useState } from "react";
import "./Submit_Your_Review.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faStar as farStar } from "@fortawesome/free-regular-svg-icons";
import { faStar as fasStar } from "@fortawesome/free-solid-svg-icons";
import Rating from "react-rating";
import { Form } from "react-bootstrap";
import Green_btn from "../../../common-components/common_btn/green_btn/Green_btn";
import Success_Modal from "../../../common-components/common_modal/success_modal/Success_Modal";
import { useForm, Controller } from "react-hook-form";
import { useDispatch, useSelector } from "react-redux";
import { postRating } from "../../../../features/rating/ratingSlice";
import Set_New_Password_Modal from "../../../common-components/common_modal/set_new_password_modal/Set_New_Password_Modal";
import Reset_Password_Modal from "../../../common-components/common_modal/reset_password_modal/Reset_Password_Modal";
import Login_Modal from "../../../common-components/common_modal/login_modal/Login_Modal";
import {
  allReviewRating,
  AvgReviewRating,
} from "../../../../features/review_rating/review_ratingSlice";

function Submit_Your_Review({ product }) {
  const [modalShow, setModalShow] = React.useState(false);
  const [images, setImages] = useState([]);

  const handleImageChange = (e) => {
    const files = Array.from(e.target.files);
    setImages(files);
  };
  const {
    register,
    handleSubmit,
    control,
    formState: { errors },
    reset,
  } = useForm({
    defaultValues: {
      name: "",
      email: "",
      review: "",
      rating: "",
    },
  });
  const dispatch = useDispatch();
  const onSubmit = async (d) => {
    const formData = new FormData();

    formData.append("ratings", d.ratings);
    formData.append("review", d.review);
    formData.append("product_id", product?.id);

    images.forEach((img, index) => {
      formData.append(`image${index}`, img);
    });

    formData.append("imageCount", images.length);

    const res = await dispatch(postRating(formData));

    if (res.meta?.requestStatus === "fulfilled") {
      setModalShow(true);
      reset();
      setImages([]);

      dispatch(
        AvgReviewRating({
          product_id: product.id,
        }),
      );

      dispatch(
        allReviewRating({
          product_id: product.id,
        }),
      );
    }
  };

  const isSignin = useSelector((state) => state.auth.is_signin);
  const [email, setEmail] = useState();
  const [contact, setContact] = useState();
  const [showResetModal, setShowResetModal] = useState(false);
  const [showSetPassModal, setShowSetPassModal] = useState(false);
  const [showSuccessModal, setShowSucsessModal] = useState(false);
  const [showAccountCreted, setShowAccountCreted] = useState(false);
  const [showLoginModal, setShowLoginModal] = useState(false);
  return (
    <>
      <section className="Submit_Your_Review">
        <div className="heading_holder">
          <h4>Submit Your Review</h4>
          <p>Add Your Rating</p>

          <Controller
            name="ratings"
            control={control}
            rules={{ required: "Rating is required" }}
            render={({ field }) => (
              <div>
                <Rating
                  {...field}
                  initialRating={field.value}
                  onChange={field.onChange}
                  emptySymbol={<FontAwesomeIcon icon={farStar} color="#ccc" />}
                  fullSymbol={
                    <FontAwesomeIcon icon={fasStar} color="#ef9920" />
                  }
                  fractions={2}
                />
                {errors.ratings && (
                  <p className="text-danger mt-1">{errors.ratings.message}</p>
                )}
              </div>
            )}
          />
        </div>

        <div className="form_holder">
          <Form>
            <div className="row">
              {/* <div className="col-md-6">
                <Form.Group className="input_group">
                  <Form.Control
                    type="text"
                    placeholder="Add Name"
                    {...register("name", { required: "Name is required" })}
                  />
                  {errors.name && (
                    <p className="text-danger mt-1">{errors.name.message}</p>
                  )}
                </Form.Group>
              </div>

              <div className="col-md-6">
                <Form.Group className="input_group">
                  <Form.Control
                    type="text"
                    placeholder="Email Address"
                    {...register("email", {
                      required: "Email is required",
                      pattern: {
                        value: /^\S+@\S+$/i,
                        message: "Invalid email format",
                      },
                    })}
                  />
                  {errors.email && (
                    <p className="text-danger mt-1">{errors.email.message}</p>
                  )}
                </Form.Group>
              </div> */}

              <div className="col-md-12">
                <Form.Group className="input_group">
                  <input
                    type="file"
                    multiple
                    accept="image/*"
                    onChange={handleImageChange}
                  />
                </Form.Group>
              </div>

              <div className="col-md-12">
                <Form.Group className="input_group">
                  <Form.Control
                    as="textarea"
                    rows={3}
                    placeholder="Write review..."
                    {...register("review", {
                      required: "Review is required",
                    })}
                  />
                  {errors.review && (
                    <p className="text-danger mt-1">{errors.review.message}</p>
                  )}
                </Form.Group>
              </div>
              {isSignin && (
                <div className="col-md-12">
                  <div className="btn_holder">
                    <Green_btn
                      btnText={"Submit Review"}
                      onClick={handleSubmit(onSubmit)}
                    />
                  </div>
                </div>
              )}
              {!isSignin && (
                <div className="col-md-12">
                  <div className="btn_holder">
                    <Green_btn
                      btnText={"Submit Review"}
                      onClick={() => {
                        setShowLoginModal(true);
                      }}
                    />
                  </div>
                </div>
              )}
            </div>
          </Form>
        </div>
      </section>

      <Login_Modal
        show={showLoginModal}
        onHide={() => {
          setShowLoginModal(false);
        }}
        setShowResetModal={() => setShowResetModal(true)}
        setShowAccountCreted={() => setShowAccountCreted(true)}
      />

      <Reset_Password_Modal
        email={email}
        setEmail={setEmail}
        contact={contact}
        setContact={setContact}
        show={showResetModal}
        onHide={() => {
          setShowResetModal(false);
        }}
        setShowSetPassModal={() => setShowSetPassModal(true)}
      />

      <Set_New_Password_Modal
        email={email}
        setEmail={setEmail}
        contact={contact}
        setContact={setContact}
        show={showSetPassModal}
        onHide={() => {
          setShowSetPassModal(false);
        }}
        setShowSucsessModal={() => setShowSucsessModal(true)}
      />

      <Success_Modal
        show={showSuccessModal}
        onHide={() => {
          setShowSucsessModal(false);
        }}
        successText="Password Reseted Successfully!"
      />

      <Success_Modal
        show={showAccountCreted}
        onHide={() => {
          setShowAccountCreted(false);
        }}
        successText="Account Created Successful!"
      />

      <Success_Modal
        show={modalShow}
        onHide={() => setModalShow(false)}
        successText="Submitted Successfully!"
      />
    </>
  );
}

export default Submit_Your_Review;
