import React, { useEffect, useState } from "react";
import "./Reason_cancelling_field_holder.css";
import { Form } from "react-bootstrap";
import Green_btn from "../common_btn/green_btn/Green_btn";

import { useDispatch, useSelector } from "react-redux";
import { cancelOrder, returnOrder } from "../../../features/order/orderSlice";

import { encodeId } from "../../../utils/common";
import Success_Modal from "../common_modal/success_modal/Success_Modal";

import Gray_Btn from "../common_btn/gray_btn/Gray_Btn";

import { ClipLoader } from "react-spinners";
import { useRouter } from "next/navigation";
function Reason_cancelling_field_holder({
  setCancelReason,
  cancelReason,
  cancelReasonId,
  selectedItems,
  order,
  error,
  setError,
  type,
}) {
  const navigate = useRouter();
  const [loder, setLoder] = useState("");
  const dispatch = useDispatch();
  const [modalShow, setModalShow] = React.useState(false);
  const handleClick = () => {
    setModalShow(true);

    setTimeout(() => {
      setModalShow(false);
      setLoder(false);
      navigate.push("/");
    }, 2000);
  };
  const onSubmit = async () => {
    const data = {
      message: cancelReason,
      products: selectedItems,
    };

    let res;
    if (type === "Return") {
      if (cancelReasonId === null) {
        setError("Return Reason Required");
        return;
      }
      if (selectedItems.length === 0) {
        setError("Select product to Return");
        return;
      }
      setLoder(true);
      data.return_reason_id = cancelReasonId;
      res = await dispatch(returnOrder({ order_id: order?.id, data }));
    }

    if (type === "Cancel") {
      if (cancelReasonId === null) {
        setError("Cancel Reason Required");
        return;
      }
      if (selectedItems.length === 0) {
        setError("Select product to Return");
        return;
      }
      setLoder(true);
      data.cancel_reason_id = cancelReasonId;
      res = await dispatch(cancelOrder({ order_id: order?.id, data }));
    }

    if (res.meta?.requestStatus === "fulfilled") {
      handleClick();
    } else if (res.meta?.requestStatus === "rejected") {
      // Optionally handle error here
    }
  };

  return (
    <>
      <section className="Reason_cancelling_field_holder">
        <Form>
          <Form.Group
            className="input_group  mb-3"
            controlId="exampleForm.ControlTextarea1"
          >
            <Form.Label>
              {type === "Cancel"
                ? "Could you tell us a reason for cancelling? (optional)"
                : type === "Return"
                  ? "Could you tell us a reason for Returning? (optional)"
                  : ""}
            </Form.Label>
            <Form.Control
              as="textarea"
              placeholder="Type a reason"
              rows={1}
              value={cancelReason}
              onChange={(e) => setCancelReason(e.target.value)}
            />
          </Form.Group>
          <p style={{ color: "red" }}>{error}</p>

          <div className="btn_holder">
            <Gray_Btn
              btnText={"Cancel"}
              onClick={() =>
                navigate.push(`/order-details/${encodeId(order?.id)}`)
              }
            />{" "}
            {loder ? (
              <>
                <div className="text-center">
                  <ClipLoader />
                </div>
              </>
            ) : (
              <Green_btn btnText={"Submit"} onClick={() => onSubmit()} />
            )}
          </div>
        </Form>
        <Success_Modal
          //  navigate={navigate("/")}
          show={modalShow}
          onHide={() => setModalShow(false)}
          successText={
            type === "Cancel"
              ? "Order Cancelled Successfully!"
              : "Order Return Successfully!"
          }
        />
      </section>
    </>
  );
}

export default Reason_cancelling_field_holder;
