import { useState, useEffect, useMemo } from "react";
import { motion, AnimatePresence } from "motion/react";
import { X, Trash2 } from "lucide-react";
import { useProfile } from "../context/ProfileContext";
import { useNavigate } from "react-router-dom";
import { ImageWithFallback } from "./figma/ImageWithFallback";
import { createPortal } from "react-dom";
import avatarFallbackImage from "../../assets/image 5.png";
import { getProfileImageUrl } from "../../services/feedService";

interface Comment {
  id: string;
  author: string;
  authorAvatar: string;
  text: string;
  timestamp: string;
  likes: number;
  isLiked: boolean;
  replies?: Comment[];
  userStageId?: string; // اضافه کردن user_stage_id
}

interface CommentsModalProps {
  isOpen: boolean;
  onClose: () => void;
  comments: Comment[];
  postAuthor: string;
  onAddComment: (text: string, parentId?: string) => void;
  onDeleteComment?: (commentId: string) => void;
  hasMoreComments?: boolean;
  isLoadingMoreComments?: boolean;
  onLoadMoreComments?: () => void;
}

export function CommentsModal({
  isOpen,
  onClose,
  comments: initialComments,
  postAuthor,
  onAddComment,
  onDeleteComment,
  hasMoreComments = false,
  isLoadingMoreComments = false,
  onLoadMoreComments,
}: CommentsModalProps) {
  const [commentText, setCommentText] = useState("");
  const [replyingTo, setReplyingTo] = useState<{ id: string; author: string } | null>(null);
  const [comments, setComments] = useState<Comment[]>(initialComments);
  const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
  const { isProfileComplete, profile } = useProfile();
  const navigate = useNavigate();
  const currentUserAvatarUrl = useMemo(() => {
    if (profile?.image && profile?.user_stage_id) {
      return getProfileImageUrl(profile.image, profile.user_stage_id);
    }
    return avatarFallbackImage;
  }, [profile?.image, profile?.user_stage_id]);

  useEffect(() => {
    setComments(initialComments);
  }, [initialComments]);

  // Prevent body scroll when modal is open
  useEffect(() => {
    const html = document.documentElement;
    const body = document.body;
    const previousBodyOverflow = body.style.overflow;
    const previousBodyTouchAction = body.style.touchAction;
    const previousBodyOverscroll = body.style.overscrollBehavior;
    const previousHtmlOverflow = html.style.overflow;
    const previousHtmlTouchAction = html.style.touchAction;
    const previousHtmlOverscroll = html.style.overscrollBehavior;

    if (isOpen) {
      body.style.overflow = "hidden";
      body.style.touchAction = "none";
      body.style.overscrollBehavior = "none";
      html.style.overflow = "hidden";
      html.style.touchAction = "none";
      html.style.overscrollBehavior = "none";
      body.classList.add("comments-modal-open");
    } else {
      body.style.overflow = previousBodyOverflow;
      body.style.touchAction = previousBodyTouchAction;
      body.style.overscrollBehavior = previousBodyOverscroll;
      html.style.overflow = previousHtmlOverflow;
      html.style.touchAction = previousHtmlTouchAction;
      html.style.overscrollBehavior = previousHtmlOverscroll;
      body.classList.remove("comments-modal-open");
    }

    return () => {
      body.style.overflow = previousBodyOverflow;
      body.style.touchAction = previousBodyTouchAction;
      body.style.overscrollBehavior = previousBodyOverscroll;
      html.style.overflow = previousHtmlOverflow;
      html.style.touchAction = previousHtmlTouchAction;
      html.style.overscrollBehavior = previousHtmlOverscroll;
      body.classList.remove("comments-modal-open");
    };
  }, [isOpen]);

  const handleSubmit = () => {
    if (commentText.trim()) {
      onAddComment(commentText, replyingTo?.id);
      setCommentText("");
      setReplyingTo(null);
    }
  };

  const handleLikeComment = (commentId: string, isReply: boolean = false, parentId?: string) => {
    setComments((prevComments) =>
      prevComments.map((comment) => {
        if (comment.id === commentId && !isReply) {
          return {
            ...comment,
            isLiked: !comment.isLiked,
            likes: comment.isLiked ? comment.likes - 1 : comment.likes + 1,
          };
        }
        if (comment.id === parentId && comment.replies) {
          return {
            ...comment,
            replies: comment.replies.map((reply) => {
              if (reply.id === commentId) {
                return {
                  ...reply,
                  isLiked: !reply.isLiked,
                  likes: reply.isLiked ? reply.likes - 1 : reply.likes + 1,
                };
              }
              return reply;
            }),
          };
        }
        return comment;
      })
    );
  };

  const toPersianNumber = (num: number): string => {
    const persianDigits = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"];
    return num
      .toString()
      .split("")
      .map((digit) => persianDigits[parseInt(digit)])
      .join("");
  };

  const CommentItem = ({
    comment,
    isReply = false,
    parentId,
  }: {
    comment: Comment;
    isReply?: boolean;
    parentId?: string;
  }) => {
    // بررسی اینکه آیا این کامنت متعلق به کاربر لاگین شده است
    const isOwnComment = profile?.user_stage_id === comment.userStageId;

    return (
      <div className={`${isReply ? "mr-12 mt-3" : ""}`} dir="rtl">
        <div className="flex gap-3 items-start">
          {/* Avatar */}
          <div
            className="w-8 h-8 rounded-full overflow-hidden flex-shrink-0"
            style={{
              border: "2px solid rgba(138, 206, 224, 0.3)",
            }}
          >
            <ImageWithFallback
              src={comment.authorAvatar}
              alt={comment.author}
              className="w-full h-full object-cover"
              fallbackSrc={avatarFallbackImage}
            />
          </div>

          {/* Comment Content */}
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 mb-1">
              <span className="text-sm font-bold text-white">{comment.author}</span>
              {comment.author === postAuthor && (
                <span
                  className="text-xs px-2 py-0.5 rounded-full"
                  style={{
                    background: "rgba(138, 206, 224, 0.2)",
                    color: "#8ACEE0",
                    border: "1px solid rgba(138, 206, 224, 0.3)",
                  }}
                >
                  نویسنده
                </span>
              )}
              <span className="text-xs text-gray-400">{comment.timestamp}</span>
            </div>

            <p className="text-sm text-white leading-relaxed mb-2">{comment.text}</p>

            {/* Actions */}
            <div className="flex items-center gap-4">
              <button
                onClick={() => setReplyingTo({ id: comment.id, author: comment.author })}
                className="text-xs font-bold text-gray-400 hover:text-gray-200 transition-colors"
              >
                پاسخ
              </button>
              {isOwnComment && onDeleteComment && (
                <button
                  onClick={() => setDeleteConfirmId(comment.id)}
                  className="text-xs font-bold text-red-400 hover:text-red-300 transition-colors flex items-center gap-1"
                >
                  <Trash2 className="w-3.5 h-3.5" />
                  <span>حذف</span>
                </button>
              )}
            </div>

            {/* Replies */}
            {comment.replies && comment.replies.length > 0 && (
              <div className="mt-3 space-y-3">
                {comment.replies.map((reply) => (
                  <CommentItem
                    key={reply.id}
                    comment={reply}
                    isReply={true}
                    parentId={comment.id}
                  />
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    );
  };

  if (typeof document === "undefined") {
    return null;
  }

  return createPortal(
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
            className="fixed inset-0 bg-black/60 z-[120] backdrop-blur-sm"
          />

          {/* Modal */}
          <motion.div
            initial={{ y: "100%" }}
            animate={{ y: 0 }}
            exit={{ y: "100%" }}
            transition={{ type: "spring", damping: 30, stiffness: 300 }}
            className="fixed left-0 right-0 z-[121] rounded-t-3xl overflow-hidden flex flex-col max-w-md mx-auto"
            style={{
              background:
                "linear-gradient(180deg, rgba(46, 27, 61, 0.98) 0%, rgba(35, 24, 62, 0.98) 100%)",
              border: "1px solid rgba(255, 170, 224, 0.22)",
              bottom: "env(safe-area-inset-bottom, 0px)",
              maxHeight: "min(82dvh, 760px)",
              height: "min(82dvh, 760px)",
            }}
          >
            {/* Header */}
            <div
              className="sticky top-0 z-10 px-4 py-3 flex items-center justify-between flex-shrink-0"
              style={{
                background: "rgba(46, 27, 61, 0.94)",
                borderBottom: "1px solid rgba(255, 170, 224, 0.2)",
              }}
              dir="rtl"
            >
              {/* Drag Indicator */}
              <div className="absolute top-2 left-1/2 -translate-x-1/2 w-12 h-1 rounded-full bg-gray-600" />

              <h2 className="text-white font-bold text-base mt-3">نظرات</h2>
              <button
                onClick={onClose}
                className="w-8 h-8 rounded-full flex items-center justify-center mt-3"
                style={{
                  background: "rgba(255, 170, 224, 0.1)",
                }}
              >
                <X className="w-5 h-5 text-gray-300" />
              </button>
            </div>

            {/* Comments List */}
            <div
              className="comments-scroll flex-1 overflow-y-auto px-4 py-4 space-y-4"
              style={{
                scrollbarWidth: "thin",
                scrollbarColor: "rgba(255, 170, 224, 0.3) transparent",
              }}
            >
              {comments.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-16">
                  <div
                    className="w-16 h-16 rounded-full flex items-center justify-center mb-3"
                    style={{
                      background: "rgba(138, 206, 224, 0.1)",
                      border: "2px solid rgba(138, 206, 224, 0.2)",
                    }}
                  >
                    <svg
                      className="w-8 h-8"
                      style={{ color: "#8ACEE0" }}
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
                      />
                    </svg>
                  </div>
                  <p className="text-gray-400 text-sm">هنوز نظری ثبت نشده است</p>
                  <p className="text-gray-500 text-xs mt-1">اولین نفری باشید که نظر می‌دهد</p>
                </div>
              ) : (
                <>
                  {comments.map((comment) => (
                    <CommentItem key={comment.id} comment={comment} />
                  ))}
                  {hasMoreComments && (
                    <div className="pt-2 text-center">
                      <motion.button
                        whileTap={{ scale: isLoadingMoreComments ? 1 : 0.97 }}
                        onClick={onLoadMoreComments}
                        disabled={isLoadingMoreComments}
                        className="px-4 py-2 rounded-full text-xs font-bold text-white"
                        style={{
                          background: "linear-gradient(135deg, rgba(96, 147, 157, 0.9) 0%, rgba(76, 127, 137, 0.9) 100%)",
                          border: "1px solid rgba(138, 206, 224, 0.3)",
                          opacity: isLoadingMoreComments ? 0.65 : 1,
                          cursor: isLoadingMoreComments ? "not-allowed" : "pointer",
                        }}
                      >
                        {isLoadingMoreComments ? "در حال بارگذاری..." : "نمایش نظرات بیشتر"}
                      </motion.button>
                    </div>
                  )}
                </>
              )}
            </div>

            {/* Input Area */}
            <div
              className="sticky bottom-0 px-4 py-3 flex-shrink-0"
              style={{
                background: "rgba(46, 27, 61, 0.9)",
                borderTop: "1px solid rgba(255, 170, 224, 0.2)",
                paddingBottom: "calc(env(safe-area-inset-bottom, 0px) + 10px)",
              }}
              dir="rtl"
            >
              {!isProfileComplete ? (
                /* پیغام برای کاربران با پروفایل ناقص */
                <div
                  className="px-4 py-3 rounded-2xl flex items-center justify-between gap-3"
                  style={{
                    background: "rgba(255, 184, 0, 0.1)",
                    border: "1.5px solid rgba(255, 184, 0, 0.3)",
                  }}
                >
                  <p className="text-sm text-gray-300 flex-1">
                    برای ثبت نظر، ابتدا پروفایل خود را تکمیل کنید
                  </p>
                  <motion.button
                    whileTap={{ scale: 0.95 }}
                    onClick={() => {
                      onClose();
                      navigate("/profile");
                    }}
                    className="px-4 py-2 rounded-full text-xs font-bold text-white flex-shrink-0"
                    style={{
                      background: "linear-gradient(135deg, #FFB800 0%, #FF9500 100%)",
                      boxShadow: "0 2px 8px rgba(255, 165, 0, 0.4)",
                    }}
                  >
                    تکمیل پروفایل
                  </motion.button>
                </div>
              ) : (
                <>
                  {/* Replying To Indicator */}
                  {replyingTo && (
                    <div
                      className="mb-2 px-3 py-2 rounded-lg flex items-center justify-between"
                      style={{
                        background: "rgba(138, 206, 224, 0.1)",
                        border: "1px solid rgba(138, 206, 224, 0.2)",
                      }}
                    >
                      <span className="text-xs text-gray-300">
                        در حال پاسخ به <span style={{ color: "#8ACEE0" }}>{replyingTo.author}</span>
                      </span>
                      <button
                        onClick={() => setReplyingTo(null)}
                        className="text-gray-400 hover:text-white"
                      >
                        <X className="w-4 h-4" />
                      </button>
                    </div>
                  )}

                  <div className="flex gap-2 items-center">
                    {/* Avatar */}
                    <div
                      className="w-8 h-8 rounded-full flex-shrink-0 overflow-hidden"
                      style={{
                        background: "linear-gradient(135deg, rgba(138, 206, 224, 0.4) 0%, rgba(62, 121, 131, 0.4) 100%)",
                        border: "1.5px solid rgba(138, 206, 224, 0.5)",
                      }}
                    >
                      <ImageWithFallback
                        src={currentUserAvatarUrl}
                        alt="پروفایل من"
                        className="w-full h-full object-cover"
                        fallbackSrc={avatarFallbackImage}
                      />
                    </div>

                    {/* Input */}
                    <input
                      type="text"
                      value={commentText}
                      onChange={(e) => setCommentText(e.target.value)}
                      onKeyPress={(e) => e.key === "Enter" && handleSubmit()}
                      placeholder={
                        replyingTo
                          ? `پاسخ به ${replyingTo.author}...`
                          : "نظر خود را بنویسید..."
                      }
                      className="flex-1 px-4 py-2.5 rounded-full text-white placeholder-gray-400 outline-none transition-all"
                      style={{
                        fontSize: 16,
                        background: "rgba(32, 76, 106, 0.3)",
                        border: "1.5px solid rgba(138, 206, 224, 0.3)",
                      }}
                      onFocus={(e) => {
                        e.target.style.border = "1.5px solid rgba(138, 206, 224, 0.6)";
                        e.target.style.boxShadow = "0 0 15px rgba(138, 206, 224, 0.3)";
                      }}
                      onBlur={(e) => {
                        e.target.style.border = "1.5px solid rgba(138, 206, 224, 0.3)";
                        e.target.style.boxShadow = "none";
                      }}
                    />

                    {/* Send Button */}
                    {commentText.trim() && (
                      <motion.button
                        initial={{ scale: 0 }}
                        animate={{ scale: 1 }}
                        exit={{ scale: 0 }}
                        whileTap={{ scale: 0.9 }}
                        onClick={handleSubmit}
                        className="px-4 py-2.5 rounded-full text-sm font-bold text-white flex-shrink-0"
                        style={{
                          background: "linear-gradient(135deg, #FFB800 0%, #FF9500 100%)",
                          boxShadow: "0 4px 15px rgba(255, 165, 0, 0.4)",
                        }}
                      >
                        ارسال
                      </motion.button>
                    )}
                  </div>
                </>
              )}
            </div>
          </motion.div>

          {/* Modal تایید حذف کامنت */}
          <AnimatePresence>
            {deleteConfirmId && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="fixed inset-0 z-[130] flex items-center justify-center p-4"
                style={{ backgroundColor: "rgba(0, 0, 0, 0.7)" }}
                onClick={() => setDeleteConfirmId(null)}
              >
                <motion.div
                  initial={{ scale: 0.9, y: 20 }}
                  animate={{ scale: 1, y: 0 }}
                  exit={{ scale: 0.9, y: 20 }}
                  onClick={(e) => e.stopPropagation()}
                  className="w-full max-w-md rounded-3xl overflow-hidden"
                  style={{
                    background: "linear-gradient(180deg, rgba(32, 76, 106, 0.98) 0%, rgba(20, 40, 60, 0.98) 100%)",
                    border: "2px solid rgba(138, 206, 224, 0.3)",
                    boxShadow: "0 20px 60px rgba(0, 0, 0, 0.5)",
                  }}
                >
                  {/* Header */}
                  <div
                    className="px-6 py-4 border-b"
                    style={{ borderColor: "rgba(138, 206, 224, 0.2)" }}
                  >
                    <h3
                      className="text-lg font-bold text-center"
                      style={{
                        color: "#FFFFFF",
                        textShadow: "0 2px 4px rgba(0, 0, 0, 0.3)",
                      }}
                    >
                      تایید حذف نظر
                    </h3>
                  </div>

                  {/* متن تایید */}
                  <div className="p-6" dir="rtl">
                    <p
                      className="text-base text-center leading-relaxed"
                      style={{
                        color: "#FFFFFF",
                        textShadow: "0 1px 2px rgba(0, 0, 0, 0.3)",
                      }}
                    >
                      آیا مطمئن هستید که می‌خواهید این نظر را حذف کنید؟
                      <br />
                      <span className="text-sm text-gray-400 mt-2 block">
                        تمام پاسخ‌های این نظر نیز حذف خواهند شد.
                      </span>
                    </p>
                  </div>

                  {/* دکمه‌های عملیاتی */}
                  <div className="px-6 py-4 flex gap-3" dir="rtl">
                    <motion.button
                      whileTap={{ scale: 0.95 }}
                      onClick={() => setDeleteConfirmId(null)}
                      className="flex-1 py-3 rounded-full font-bold text-white"
                      style={{
                        background: "linear-gradient(135deg, rgba(96, 96, 96, 0.9) 0%, rgba(64, 64, 64, 0.9) 100%)",
                        boxShadow: "0 4px 12px rgba(0, 0, 0, 0.3)",
                      }}
                    >
                      انصراف
                    </motion.button>
                    <motion.button
                      whileTap={{ scale: 0.95 }}
                      onClick={() => {
                        if (onDeleteComment) {
                          onDeleteComment(deleteConfirmId);
                        }
                        setDeleteConfirmId(null);
                      }}
                      className="flex-1 py-3 rounded-full font-bold text-white"
                      style={{
                        background: "linear-gradient(135deg, #ef4444 0%, #dc2626 100%)",
                        boxShadow: "0 4px 12px rgba(239, 68, 68, 0.4)",
                      }}
                    >
                      حذف نظر
                    </motion.button>
                  </div>
                </motion.div>
              </motion.div>
            )}
          </AnimatePresence>
        </>
      )}
    </AnimatePresence>,
    document.body
  );
}
