"use client";

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

function ProjectWorkroomRate({
  projectId,
  selected_user,
}: {
  projectId: string;
  selected_user: string | SelectedUser;
}) {
  const { request } = useAxios();
  const router = useRouter();
  const [rating, setRating] = useState<number>(0);
  const [commentText, setCommentText] = useState<string>("");
  const [hasRatedUser, setHasRatedUser] = useState(false);

  const targetUserId =
    typeof selected_user === "string" ? selected_user : selected_user?._id;

  useEffect(() => {
    if (!targetUserId) return;

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

    fetchRatingStatus();
  }, [targetUserId, request]);

  const doneHandler = async () => {
    if (!commentText) {
      toast.error("ثبت نظر الزامی است.");
      return;
    }
    if (!hasRatedUser && !rating) {
      toast.error("ثبت امتیاز الزامی است.");
      return;
    }
    try {
      const body: Record<string, unknown> = {
        project_id: projectId,
        comment: commentText,
        user_id: targetUserId,
      };
      if (!hasRatedUser && rating) body.rate = rating;

      await request("POST", "/projects/done/web", body);
      router.push("/settings/workroom");
    } catch (error: unknown) {
      console.log(error);
    }
  };

  const cancleHandler = async () => {
    if (!commentText) {
      toast.error("ثبت نظر الزامی است.");
      return;
    }
    if (!hasRatedUser && !rating) {
      toast.error("ثبت امتیاز الزامی است.");
      return;
    }
    try {
      const body: Record<string, unknown> = {
        project_id: projectId,
        comment: commentText,
        user_id: targetUserId,
      };
      if (!hasRatedUser && rating) body.rate = rating;

      await request("POST", "/projects/cancle", body);
      router.push("/settings/workroom");
    } catch (error: unknown) {
      console.log(error);
    }
  };

  return (
    <div className="flex flex-col items-center gap-3 w-full my-7">
      <textarea
        placeholder="نظر شما"
        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 `}
      />
      {!hasRatedUser && (
        <Rate
          value={rating}
          onChange={(value) => setRating(value)}
          count={5}
          style={{ fontSize: "28px" }}
        />
      )}
      <div className="grid grid-cols-2 w-full max-w-sm gap-4 text-sm">
        <RoundedButton
          onClick={doneHandler}
          className="w-full h-9 !border-[#667AC1] text-[#667AC1]"
        >
          اتمام پروژه
        </RoundedButton>
        <RoundedButton
          onClick={cancleHandler}
          className="w-full h-9 !border-[#EA5B5B] text-[#EA5B5B]"
        >
          لغو پروژه
        </RoundedButton>
      </div>
    </div>
  );
}

export default ProjectWorkroomRate;
