"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";
import { useTranslation } from "react-i18next";

function ProjectWorkroomRate({
  projectId,
  selected_user,
}: {
  projectId: string;
  selected_user: string | SelectedUser;
}) {
  const { t } = useTranslation("common");
  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(t("projects.workroom.commentRequired"));
      return;
    }
    if (!hasRatedUser && !rating) {
      toast.error(t("projects.workroom.ratingRequired"));
      return;
    }
    try {
      // نظر و امتیاز تا برگشت از درگاه پرداخت نگه داشته می‌شود تا بعد از پرداخت باقی‌مانده ثبت شود
      if (typeof window !== "undefined") {
        sessionStorage.setItem(
          `project-done-${projectId}`,
          JSON.stringify({
            comment: commentText,
            rate: !hasRatedUser && rating ? rating : undefined,
            user_id: targetUserId,
          })
        );
      }

      const response = await request<{ authority?: string; paymentUrl?: string }>(
        "POST",
        "/projects/initiate-completion-payment/web",
        { projectId }
      );
      if (response?.paymentUrl) {
        router.push(response.paymentUrl);
      } else if (response?.authority) {
        router.push(`https://www.zarinpal.com/pg/StartPay/${response.authority}`);
      }
    } catch (error: unknown) {
      const message =
        (error as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  const cancleHandler = async () => {
    if (!commentText) {
      toast.error(t("projects.workroom.commentRequired"));
      return;
    }
    if (!hasRatedUser && !rating) {
      toast.error(t("projects.workroom.ratingRequired"));
      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={t("projects.workroom.commentPlaceholder")}
        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" }}
        />
      )}
      <p className="max-w-sm text-center text-[11px] text-neutral-500">
        {t("settings.workroom.payRemainingHint")}
      </p>
      <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]"
        >
          {t("projects.workroom.completeProject")}
        </RoundedButton>
        <RoundedButton
          onClick={cancleHandler}
          className="w-full h-9 !border-[#EA5B5B] text-[#EA5B5B]"
        >
          {t("projects.workroom.cancelProject")}
        </RoundedButton>
      </div>
    </div>
  );
}

export default ProjectWorkroomRate;
