"use client";

import { useFollowUserMutation } from "@/api/auth.api";
import {
  useBookmarkEntityMutation,
  useCreateAnswerCommentMutation,
  useGetAnswerCommentsQuery,
  useLikeEntityMutation,
} from "@/api/seaqa.api";
import { IAnswer, IAnswerComment } from "@/api/types/questions";
import SeaQaCommentSkeleton from "@/components/skeleton/SeaQaCommentSkeleton";
import { useAppSelector } from "@/redux/hooks";
import Image from "next/image";
import Link from "next/link";
import React, { useState } from "react";
import { toast } from "react-hot-toast";
import Avatar from "@/components/common/Avatar";

function formatDate(iso: string): string {
  return new Date(iso).toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
  });
}

interface SeaQaAnswerCardProps {
  answer: IAnswer;
}

interface CommentItemProps {
  comment: IAnswerComment;
  answerId: number;
}

const CommentItem: React.FC<CommentItemProps> = ({ comment, answerId }) => {
  const [showReplyInput, setShowReplyInput] = useState(false);
  const [replyText, setReplyText] = useState("");
  const [createComment, { isLoading: postingReply }] =
    useCreateAnswerCommentMutation();
  const currentUser = useAppSelector((state) => state.auth.user);

  const handleReplySubmit = async () => {
    const text = replyText.trim();
    if (!text) return;
    try {
      await createComment({
        answerId,
        content: text,
        parentId: comment.id,
      }).unwrap();
      setReplyText("");
      setShowReplyInput(false);
    } catch {
      toast.error("Failed to post reply.");
    }
  };

  return (
    <div className="flex flex-col gap-2 w-full">
      <div className="flex gap-2.5 w-full">
        <Avatar
          src={comment.author.profileImage?.filePath}
          name={comment.author.name}
          size="sm"
        />
        <div className="flex-1 min-w-0">
          <div className="flex items-baseline gap-2 flex-wrap">
            <p className="text-[12px] font-semibold text-[#111827]">
              {comment.author.name}
            </p>
            <p className="text-[10px] text-[#9ca3af]">
              {comment.author.rank?.name
                ? `${comment.author.rank.name} · `
                : ""}
              {formatDate(comment.createdAt)}
            </p>
          </div>
          <p className="text-[12px] text-[#374151] leading-normal mt-0.5 break-words whitespace-pre-wrap">
            {comment.content}
          </p>
          <button
            type="button"
            onClick={() => setShowReplyInput(!showReplyInput)}
            className="mt-1 text-[10px] font-semibold text-[#3b82f6] bg-transparent border-none cursor-pointer p-0"
          >
            Reply
          </button>
        </div>
      </div>

      {/* Replies list */}
      {comment.replies && comment.replies.length > 0 && (
        <div className="ml-9 flex flex-col gap-2.5 border-l border-[#e5e7eb] pl-3">
          {comment.replies.map((reply) => (
            <div key={reply.id} className="flex gap-2">
              <Avatar
                src={reply.author.profileImage?.filePath}
                name={reply.author.name}
                size="xs"
              />
              <div className="flex-1 min-w-0">
                <div className="flex items-baseline gap-2 flex-wrap">
                  <p className="text-[12px] font-semibold text-[#111827]">
                    {reply.author.name}
                  </p>
                  <p className="text-[10px] text-[#9ca3af]">
                    {reply.author.rank?.name
                      ? `${reply.author.rank.name} · `
                      : ""}
                    {formatDate(reply.createdAt)}
                  </p>
                </div>
                <p className="text-[12px] text-[#374151] leading-normal mt-0.5 break-words whitespace-pre-wrap">
                  {reply.content}
                </p>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Reply input field */}
      {showReplyInput && (
        <div className="ml-9">
          <div className="flex gap-2 items-start">
            <Avatar
              src={currentUser?.profileImage}
              name={currentUser?.name ?? "Me"}
              size="xs"
            />
            <div className="flex-1">
              <textarea
                rows={2}
                value={replyText}
                onChange={(e) => setReplyText(e.target.value)}
                placeholder="Write a reply…"
                className="w-full text-[12px] border border-[#e5e7eb] rounded-lg px-2.5 py-1.5 resize-none outline-none font-[inherit] bg-white text-black"
              />
              <div className="flex gap-1.5 mt-1.5">
                <button
                  type="button"
                  onClick={() => setShowReplyInput(false)}
                  className="px-2.5 py-1 text-[10px] font-medium rounded-md border border-[#e5e7eb] text-[#4b5563] bg-white cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  type="button"
                  onClick={handleReplySubmit}
                  disabled={postingReply}
                  className="px-2.5 py-1 text-[10px] font-semibold rounded-md bg-[#2563eb] text-white border-none cursor-pointer disabled:opacity-50"
                >
                  Reply
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const SeaQaAnswerCard: React.FC<SeaQaAnswerCardProps> = ({ answer }) => {
  const [showComments, setShowComments] = useState(false);
  const [newComment, setNewComment] = useState("");
  const [visibleCount, setVisibleCount] = useState(10);
  const [hasComments, setHasComments] = useState(answer.commentsCount > 0);
  const [isLiked, setIsLiked] = useState(answer.isLiked);
  const [likesCount, setLikesCount] = useState(answer.likesCount);
  const [isBookmarked, setIsBookmarked] = useState(answer.isBookmarked);
  const [likeEntity, { isLoading: liking }] = useLikeEntityMutation();
  const [followUser, { isLoading: followLoading }] = useFollowUserMutation();
  const [bookmarkEntity, { isLoading: bookmarking }] =
    useBookmarkEntityMutation();

  const currentUser = useAppSelector((state) => state.auth.user);
  const currentUserId = currentUser?.id ? Number(currentUser.id) : null;
  const isOwn = currentUserId === answer.author.id;

  const handleLike = async () => {
    // Users cannot like their own answer.
    if (isOwn) return;
    const nextLiked = !isLiked;
    setIsLiked(nextLiked);
    setLikesCount((c) => c + (nextLiked ? 1 : -1));
    try {
      await likeEntity({ entityType: "answer", entityId: answer.id }).unwrap();
    } catch {
      setIsLiked(isLiked);
      setLikesCount(answer.likesCount);
    }
  };

  const handleFollowToggle = async () => {
    try {
      await followUser(answer.author.id).unwrap();
    } catch {
      toast.error("Failed to follow/unfollow user.");
    }
  };

  const handleBookmark = async () => {
    const next = !isBookmarked;
    setIsBookmarked(next);
    try {
      await bookmarkEntity({
        entityType: "answer",
        entityId: answer.id,
      }).unwrap();
    } catch {
      setIsBookmarked(isBookmarked);
    }
  };

  const { data: comments = [], isFetching } = useGetAnswerCommentsQuery(
    answer.id,
    { skip: !showComments || !hasComments },
  );

  const [createComment, { isLoading: postingComment }] =
    useCreateAnswerCommentMutation();

  const handleAddComment = async () => {
    const text = newComment.trim();
    if (!text) return;
    try {
      await createComment({
        answerId: answer.id,
        content: text,
      }).unwrap();
      setNewComment("");
      setHasComments(true);
      setShowComments(true);
    } catch {
      toast.error("Failed to post comment.");
    }
  };

  const visibleComments = comments.slice(0, visibleCount);
  const remainingCount = Math.max(0, comments.length - visibleComments.length);

  const authorRank = answer.author.rank?.name;
  // Link the author's avatar/name to their public profile, unless this is the
  // current user's own answer (no point linking to yourself).
  const profileHref = `/user-profile?userId=${answer.author.id}`;

  return (
    <div className="bg-white rounded-2xl px-6 py-4 flex flex-col gap-3 w-full">
      {/* Header */}
      <div className="flex items-center gap-3">
        {isOwn ? (
          <Avatar
            src={answer.author.profileImage?.filePath}
            name={answer.author.name}
            size="md"
          />
        ) : (
          <Link href={profileHref} className="shrink-0 no-underline">
            <Avatar
              src={answer.author.profileImage?.filePath}
              name={answer.author.name}
              size="md"
            />
          </Link>
        )}
        <div className="min-w-0 flex-1">
          {isOwn ? (
            <p className="text-[14px] font-semibold text-[#111827] leading-[1.3] truncate">
              {answer.author.name}
            </p>
          ) : (
            <Link
              href={profileHref}
              className="block text-[14px] font-semibold text-[#111827] leading-[1.3] truncate hover:text-[#3b82f6] transition-colors no-underline"
            >
              {answer.author.name}
            </Link>
          )}
          {/* Keep the meta on one line: a long rank truncates with an
              ellipsis while the date stays fully visible. */}
          <p className="text-[12px] text-[#9ca3af] flex items-center gap-1 min-w-0">
            {authorRank && (
              <>
                <span className="truncate">{authorRank}</span>
                <span className="shrink-0">·</span>
              </>
            )}
            <span className="shrink-0">{formatDate(answer.createdAt)}</span>
          </p>
        </div>
        {!isOwn && (
          <button
            type="button"
            onClick={handleFollowToggle}
            disabled={followLoading}
            className={`shrink-0 px-3.5 py-1 rounded-full text-[12px] font-semibold font-[Arial] bg-white cursor-pointer border disabled:opacity-50 ${
              answer.author.isFollowed
                ? "border-[#d1d5db] text-[#6b7280]"
                : "border-[#93c5fd] text-[#3b82f6]"
            }`}
          >
            {answer.author.isFollowed ? "Following" : "Follow"}
          </button>
        )}
        <button
          type="button"
          onClick={handleBookmark}
          disabled={bookmarking}
          className="shrink-0 bg-transparent border-none cursor-pointer p-0.5 flex items-center disabled:opacity-50"
        >
          <Image
            src={
              isBookmarked
                ? "/assets/images/bookmark_lock.svg"
                : "/assets/images/bookmark_un.svg"
            }
            alt={isBookmarked ? "Bookmarked" : "Bookmark"}
            width={20}
            height={20}
          />
        </button>
      </div>

      {/* Body */}
      <div
        className="prose-rich break-words pl-12"
        dangerouslySetInnerHTML={{ __html: answer.body }}
      />

      {/* Comments section */}
      <div className="mt-1 pl-12">
        {/* Toggle row */}
        <div className="flex items-center justify-between">
          <button
            type="button"
            onClick={() => setShowComments(!showComments)}
            className="flex items-center gap-1.5 text-[12px] text-[#6b7280] bg-transparent border-none cursor-pointer p-0"
          >
            <svg
              width="14"
              height="14"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                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>
            <span className="font-medium font-[Arial]">
              {answer.commentsCount} Comment
              {answer.commentsCount !== 1 ? "s" : ""}
            </span>
            <svg
              width="12"
              height="12"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              viewBox="0 0 24 24"
              className={`transition-transform duration-200 ${showComments ? "rotate-180" : ""}`}
            >
              <path d="M19 9l-7 7-7-7" />
            </svg>
          </button>
          <button
            type="button"
            onClick={handleLike}
            disabled={liking || isOwn}
            className="flex items-center gap-1.5 bg-transparent border-none cursor-pointer p-0 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <svg
              width="14"
              height="14"
              fill={isLiked ? "#ef4444" : "none"}
              stroke={isLiked ? "#ef4444" : "#d1d5db"}
              strokeWidth="2"
              viewBox="0 0 24 24"
            >
              <path d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
            </svg>
            <span
              className={`text-[11px] font-medium ${isLiked ? "text-[#ef4444]" : "text-[#9ca3af]"}`}
            >
              {likesCount}
            </span>
          </button>
        </div>

        {/* Comments list */}
        {showComments && (
          <div className="mt-3 flex flex-col gap-4 border-l-2 border-[#e5e7eb] pl-4">
            {isFetching && comments.length === 0 ? (
              <>
                <SeaQaCommentSkeleton />
                <SeaQaCommentSkeleton />
              </>
            ) : (
              visibleComments.map((comment) => (
                <CommentItem
                  key={comment.id}
                  comment={comment}
                  answerId={answer.id}
                />
              ))
            )}

            {remainingCount > 0 && (
              <button
                onClick={() => setVisibleCount((c) => c + 10)}
                className="self-start text-[12px] font-semibold text-[#3b82f6] bg-transparent border-none cursor-pointer p-0 underline"
              >
                See {remainingCount} more Comments
              </button>
            )}

            <div className="flex gap-2 items-start pt-1">
              <Avatar
                src={currentUser?.profileImage}
                name={currentUser?.name ?? "Me"}
                size="sm"
              />
              <div className="flex-1">
                <textarea
                  rows={2}
                  value={newComment}
                  onChange={(e) => setNewComment(e.target.value)}
                  placeholder="Write a comment…"
                  className="w-full text-[12px] border border-[#e5e7eb] rounded-xl px-3 py-2 resize-none outline-none font-[inherit] bg-white text-black"
                />
                {newComment.trim() !== "" && (
                  <div className="text-right mt-1.5">
                    <button
                      type="button"
                      onClick={handleAddComment}
                      disabled={postingComment}
                      className="px-3 py-1 text-[10px] font-semibold rounded-md bg-[#2563eb] text-white border-none cursor-pointer disabled:opacity-50"
                    >
                      Post Comment
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default SeaQaAnswerCard;
