"use client";

import React, { useEffect, useState } from "react";
import "./Delivered_order.css";
import Breadcrumb_comp from "../../common-components/breadcrumb-comp/Breadcrumb_comp";
import Order_id_holder from "../order_details/order_id_holder/Order_id_holder";
import Order_details_table from "../order_details/order_details_table/Order_details_table";
import Receiver_info_holder from "../order_details/receiver_info_holder/Receiver_info_holder";
import Payment_Summary from "../order_details/payment_Summary/Payment_Summary";
import { decodeId } from "../../../utils/common";
import { useDispatch, useSelector } from "react-redux";
import { getOrder } from "../../../features/order/orderSlice";

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Green_btn from "../../common-components/common_btn/green_btn/Green_btn";
import Green_Outline_Btn from "../../common-components/common_btn/green_outline_btn/Green_Outline_Btn";
import Rating from "react-rating";
import { faStar as farStar } from "@fortawesome/free-regular-svg-icons";
import { faStar as fasStar } from "@fortawesome/free-solid-svg-icons";
import { Form } from "react-bootstrap";
import Delete_Modal from "../../common-components/common_modal/delete_modal/Delete_Modal";
import { Controller, useForm } from "react-hook-form";
import { contactusForm } from "../../../features/contact_us/contactusSlice";
import { postRating } from "../../../features/rating/ratingSlice";
import Success_Modal from "../../common-components/common_modal/success_modal/Success_Modal";
import { useParams } from "next/navigation";

function Delivered_order() {
  const [modalShow, setModalShow] = React.useState(false);
  const breadcrumbs = [
    { label: "Home", link: "/", isActive: false },
    { label: "My Orders", link: "/account", isActive: false },
    { label: "Delivered Order", link: "", isActive: true },
  ];

  const dispatch = useDispatch();
  const { id } = useParams(); // encoded ID from URL
  const [orderId, setOrderId] = useState(null); // decoded ID

  useEffect(() => {
    if (id) {
      const decoded = decodeId(id);
      setOrderId(decoded);
    }
  }, [id]);

  const order = useSelector((state) => state.order.order);
  useEffect(() => {
    if (orderId) {
      // Ensure ID is valid before dispatching
      dispatch(getOrder({ id: orderId, order_status_id: "" }));
    }
  }, [dispatch, orderId]);

  const {
    register,
    handleSubmit,
    control,
    getValues,
    formState: { errors },
  } = useForm({
    defaultValues: {
      rating: "",
      review: "",
    },
  });

  const [showSuccessModal, setShowSucsessModal] = useState(false);
  const [productId, setProductId] = useState("");
  const [showReviewRating, setShowReviewRating] = useState(false);
  const onSubmit = async (d) => {
    const data = {
      ratings: d.ratings,
      review: d.review,
      product_id: productId,
      order_id: order?.id,
    };

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

    if (res.meta?.requestStatus === "fulfilled") {
      setShowSucsessModal(true);
      dispatch(getOrder({ id: orderId, order_status_id: "" }));
    } else if (res.meta?.requestStatus === "rejected") {
    }
  };

  return (
    <>
      <section className="Delivered_order Order_details">
        <Breadcrumb_comp breadcrumbs={breadcrumbs} />

        <div className="container">
          <div className="row">
            <div className=" col-lg-8 col-md-7">
              <Order_id_holder order={order} headingText="Order ID #859865" />

              <Order_details_table
                order={order}
                setProductId={setProductId}
                productId={productId}
                type="Deliver"
                setShowReviewRating={setShowReviewRating}
                showReviewRating={showReviewRating}
              />
              {showReviewRating && (
                <div className="Ratings_and_Review">
                  <div className="">
                    {/* <Form onSubmit={handleSubmit(onSubmit)}> */}
                    <Form>
                      <Form.Group
                        className="mb-3"
                        controlId="exampleForm.ControlTextarea1"
                      >
                        <div className="lable_holder">
                          <Form.Label>Add Ratings and Review</Form.Label>

                          {/* Rating field with Controller */}
                          <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="#FFD700"
                                    />
                                  }
                                  fractions={2}
                                />
                                {errors.rating && (
                                  <p className="text-danger mt-1">
                                    {errors.rating.message}
                                  </p>
                                )}
                              </div>
                            )}
                          />
                        </div>

                        {/* Review textarea */}
                        <Form.Control
                          as="textarea"
                          placeholder="Type a product review here"
                          rows={3}
                          {...register("review", {
                            required: "Review is required",
                          })}
                        />
                        {errors.review && (
                          <p className="text-danger">{errors.review.message}</p>
                        )}
                      </Form.Group>

                      <div className="btn_holder">
                        <Green_btn
                          btnText={"Submit"}
                          type="submit"
                          onClick={handleSubmit(onSubmit)}
                        />
                        <Green_Outline_Btn btnText={"Cancel"} />
                      </div>
                    </Form>
                    {/* <Form>
                                        <Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
                                            <div className="lable_holder">
                                                <Form.Label>Add Ratings and Review</Form.Label>
                                                <Rating
                                                    initialRating={4}
                                                    emptySymbol={<FontAwesomeIcon icon={farStar} color="#ccc" />}
                                                    fullSymbol={<FontAwesomeIcon icon={fasStar} color="#FFD700" />}
                                                    fractions={2}
                                                />
                                            </div>
                                            <Form.Control as="textarea" placeholder="Type a product review here" rows={3} />
                                        </Form.Group>

                                        <div className="btn_holder">
                                            <Green_btn btnText={"Submit"} onClick={() => setModalShow(true)} />
                                            <Green_Outline_Btn btnText={"Cancel"} />
                                        </div>
                                    </Form> */}
                  </div>
                </div>
              )}
            </div>
            <div className="col-lg-4 col-md-5">
              <Receiver_info_holder order={order} />

              <Payment_Summary order={order} />
            </div>
          </div>
        </div>
      </section>

      <Delete_Modal
        show={modalShow}
        onHide={() => setModalShow(false)}
        successText="Rating and Reviews Submited Sucessfuly"
      />

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

export default Delivered_order;
