import React, { useState, useEffect } from "react";
import Rate from "rc-rate";
import "rc-rate/assets/index.css";
import "@/styles/rc-rate-custom.css";
import Modal from "@/components/elements/Modal";
import useAxios from "@/hooks/useAxios";
import { IOffers } from "@/types/types";
import RoundedButton from "@/components/elements/RoundedButton";
import toast from "react-hot-toast";

type CommentModalProps = {
  isOpen: boolean;
  onClose: () => void;
  item: IOffers | null;
};

function CommentModal({ isOpen, onClose, item }: CommentModalProps) {
  const { request } = useAxios();
  const [rating, setRating] = useState<number>(0);
  const [commentText, setCommentText] = useState<string>("");
  const [hasRatedUser, setHasRatedUser] = useState(false);

  const receiverId = item?.receiver?._id;

  useEffect(() => {
    if (!isOpen || !receiverId) return;

    const fetchRatingStatus = async () => {
      try {
        const response = (await request(
          "GET",
          `/users/comments?user_id=${receiverId}&limit=1`
        )) as { has_rated?: boolean };
        setHasRatedUser(!!response?.has_rated);
      } catch {
        setHasRatedUser(false);
      }
    };

    fetchRatingStatus();
  }, [isOpen, receiverId, request]);

  const submitComment = async () => {
    if (!commentText) {
      toast.error("متن نظر الزامی است.");
      return;
    }
    if (!hasRatedUser && !rating) {
      toast.error("امتیاز الزامی است.");
      return;
    }
    try {
      const body: Record<string, unknown> = {
        offerId: item ? item?._id : "",
        comment: commentText,
        user_id: receiverId,
      };
      if (!hasRatedUser && rating) body.rate = rating;

      await request("POST", "/offers/comment", body);
      onClose();
    } catch (error: unknown) {
      console.log(error);
    }
  };

  return (
    <Modal height="440px" isOpen={isOpen} onClose={onClose}>
      <div className="flex flex-col items-center gap-6 mt-5">
        <span>ثبت نظر</span>
        {!hasRatedUser && (
          <Rate
            value={rating}
            onChange={(value) => setRating(value)}
            count={5}
            style={{ fontSize: "28px" }}
          />
        )}
        <textarea
          value={commentText}
          onChange={(e) => setCommentText(e.target.value)}
          className={`w-full p-4 h-20 rounded-3xl border border-border-secondary-light dark:border-border-secondary-dark bg-secondary-light dark:bg-secondary-dark font-medium `}
        />
        <RoundedButton className="h-9 w-36 mt-4" onClick={submitComment}>
          ثبت
        </RoundedButton>
      </div>
    </Modal>
  );
}

export default CommentModal;
