import React, { useState, useEffect } from "react";
import Modal from "../../elements/Modal";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import RoundedInput from "@/components/elements/RoundedInput";
import useAxios from "@/hooks/useAxios";
import toast from "react-hot-toast";
import Rate from "rc-rate";
import "rc-rate/assets/index.css";
import "@/styles/rc-rate-custom.css";
import BoldIcon from "@/components/ui/BoldIcon";
import ProfileAvatar from "@/components/main/ProfileAvatar";
import { useRequireAuth } from "@/lib/auth/useRequireAuth";

export interface Comments {
  _id: string;
  comment: string;
  rating: number | null;
  createdAt: string;
  status: string;
  user: User;
  project: string | null;
  post_id?: string;
  postId?: string;
}

export interface User {
  profile_image: string | null;
  user_name: string;
  is_verified: string;
  _id: string;
}

type CommentsModalProps = {
  isOpen: boolean;
  onClose: () => void;
  userId: string;
  postId?: string;
};

function CommentsModal({ isOpen, onClose, userId, postId }: CommentsModalProps) {
  const [hasRatedProfile, setHasRatedProfile] = useState(false);
  const [newMessage, setNewMessage] = useState("");
  const [rating, setRating] = useState<number>(0);
  const { request } = useAxios();
  const requireAuth = useRequireAuth();

  const { data, containerRef, isFetchingNextPage, refetch } = useInfiniteScroll({
    endpoint: "/users/comments",
    queryKey: ["comments", userId, postId || "profile"],
    params: postId
      ? { user_id: userId, post_id: postId }
      : { user_id: userId },
  });

  useEffect(() => {
    const hasRated = data?.pages?.[0]?.has_rated;
    if (typeof hasRated === "boolean") {
      setHasRatedProfile(hasRated);
    }
  }, [data, isOpen, userId]);

  const allComments =
    data?.pages?.flatMap((page) => page?.comments || []) || [];

  const filteredComments = postId
    ? allComments.filter(
        (c: Comments) => c.post_id === postId || c.postId === postId
      )
    : allComments;

  const sendMessageHandler = async () => {
    if (!requireAuth()) return;
    if (!newMessage.trim()) {
      toast.error("ثبت نظر الزامی است.");
      return;
    }
    if (newMessage.length > 500) {
      toast.error("کامنت نمی‌تواند بیش از 500 کاراکتر باشد.");
      return;
    }
    if (!hasRatedProfile && !rating) {
      toast.error("برای اولین نظر، ثبت امتیاز الزامی است.");
      return;
    }

    try {
      const body: Record<string, unknown> = {
        comment: newMessage,
        user_id: userId,
      };
      if (!hasRatedProfile && rating) body.rate = rating;
      if (postId) body.post_id = postId;

      await request("POST", "/users/comments", body);
      if (!hasRatedProfile && rating) {
        setHasRatedProfile(true);
      }
      setNewMessage("");
      setRating(0);
      refetch?.();
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} height="min(82vh, 520px)">
      <div className="flex h-full flex-col">
        <h3 className="shrink-0 border-b border-neutral-200/60 px-4 py-3 text-center font-bold dark:border-neutral-700">
          نظرات
        </h3>
        <div ref={containerRef} className="min-h-0 flex-1 overflow-y-auto p-4">
          {filteredComments.length === 0 && !isFetchingNextPage ? (
            <p className="text-center text-gray-500">نظری وجود ندارد.</p>
          ) : (
            filteredComments.map((item: Comments) => (
              <div
                key={item?._id}
                className="mb-4 flex flex-row border-b border-neutral-100 pb-2 dark:border-neutral-800"
              >
                <ProfileAvatar
                  src={item?.user?.profile_image}
                  alt={item?.user?.user_name || "کاربر"}
                  size="chat"
                  rounded="full"
                  className="ml-2"
                />
                <div className="text-sm">
                  <div className="font-semibold">{item?.user?.user_name}</div>
                  {item?.rating != null && item.rating > 0 && (
                    <span className="text-amber-500">★ {item.rating}</span>
                  )}
                  <p className="mt-1">{item.comment}</p>
                </div>
              </div>
            ))
          )}
        </div>
        <div className="shrink-0 border-t border-neutral-200/60 p-4 pb-[calc(5.5rem+env(safe-area-inset-bottom))] dark:border-neutral-700">
          {!hasRatedProfile && (
            <div className="mb-3 flex justify-center">
              <Rate
                value={rating}
                onChange={(v) => setRating(v)}
                count={5}
                style={{ fontSize: 28, color: "#f59e0b" }}
              />
            </div>
          )}
          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={sendMessageHandler}
              className="ig-dm-send-btn gentle-transition flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-white active:scale-90"
            >
              <BoldIcon name="send-2" size={18} tinted className="text-current" />
            </button>
            <RoundedInput
              value={newMessage}
              onChange={(e) => {
                if (e.target.value.length <= 500) setNewMessage(e.target.value);
              }}
              className="flex-1"
            />
          </div>
        </div>
      </div>
    </Modal>
  );
}

export default CommentsModal;
