"use client";
import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { ThumbsUp, ThumbsDown, Reply as ReplyIcon } from "lucide-react";

type Comment = {
  id: string;
  authorName: string;
  content: string;
  parentId: string | null;
  createdAt: string;
  likeCount: number;
  dislikeCount: number;
  myVote: number;
};

export default function Comments({ postId }: { postId: string }) {
  const { data: session } = useSession();
  const router = useRouter();
  const [comments, setComments] = useState<Comment[]>([]);
  const [newComment, setNewComment] = useState("");
  const [replyingTo, setReplyingTo] = useState<string | null>(null);
  const [replyText, setReplyText] = useState("");
  const [expanded, setExpanded] = useState(false);
  const [visibleCount, setVisibleCount] = useState(10);

  async function load() {
    const res = await fetch(`/api/posts/${postId}/comments`);
    setComments(await res.json());
  }

  useEffect(() => {
    if (expanded) load();
  }, [expanded]);

  async function submit(content: string, parentId?: string) {
    if (!session?.user) {
      router.push("/login");
      return;
    }
    if (!content.trim()) return;
    await fetch(`/api/posts/${postId}/comments`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ content, parentId }),
    });
    setNewComment("");
    setReplyText("");
    setReplyingTo(null);
    load();
  }

  async function vote(commentId: string, value: 1 | -1) {
    if (!session?.user) {
      router.push("/login");
      return;
    }
    await fetch(`/api/comments/${commentId}/like`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ value }),
    });
    load();
  }

  const topLevel = comments.filter((c) => !c.parentId);
  const visibleTopLevel = topLevel.slice(0, visibleCount);
  const repliesOf = (id: string) => comments.filter((c) => c.parentId === id);

  if (!expanded) {
    return (
      <button onClick={() => setExpanded(true)} className="text-xs text-neutral-500 hover:text-white">
        💬 Comments
      </button>
    );
  }

  return (
    <div className="mt-3 pt-3 border-t border-neutral-800">
      <div className="flex gap-2 mb-3">
        <input
          value={newComment}
          onChange={(e) => setNewComment(e.target.value)}
          placeholder="Write a comment..."
          className="flex-1 bg-neutral-900 border border-neutral-800 rounded-full px-3 py-1.5 text-xs outline-none focus:border-red-600"
          onKeyDown={(e) => e.key === "Enter" && submit(newComment)}
        />
        <button onClick={() => submit(newComment)} className="text-xs text-red-500 font-semibold px-2">
          Post
        </button>
      </div>

      <div className="space-y-3">
        {visibleTopLevel.map((c) => (
          <div key={c.id}>
            <div className="flex items-start justify-between">
              <div>
                <span className="text-xs font-semibold">{c.authorName}</span>
                <p className="text-xs text-neutral-300">{c.content}</p>
              </div>
            </div>
            <div className="flex items-center gap-3 mt-1 text-[11px] text-neutral-500">
              <button onClick={() => vote(c.id, 1)} className={`flex items-center gap-1 ${c.myVote === 1 ? "text-green-500" : "hover:text-white"}`}>
                <ThumbsUp size={12} /> {c.likeCount}
              </button>
              <button onClick={() => vote(c.id, -1)} className={`flex items-center gap-1 ${c.myVote === -1 ? "text-red-500" : "hover:text-white"}`}>
                <ThumbsDown size={12} /> {c.dislikeCount}
              </button>
              <button onClick={() => setReplyingTo(replyingTo === c.id ? null : c.id)} className="flex items-center gap-1 hover:text-white">
                <ReplyIcon size={12} /> Reply
              </button>
              <span>{new Date(c.createdAt).toLocaleDateString()}</span>
            </div>

            {replyingTo === c.id && (
              <div className="flex gap-2 mt-2 ml-4">
                <input
                  value={replyText}
                  onChange={(e) => setReplyText(e.target.value)}
                  placeholder={`Reply to ${c.authorName}...`}
                  className="flex-1 bg-neutral-900 border border-neutral-800 rounded-full px-3 py-1.5 text-xs outline-none focus:border-red-600"
                  onKeyDown={(e) => e.key === "Enter" && submit(replyText, c.id)}
                />
                <button onClick={() => submit(replyText, c.id)} className="text-xs text-red-500 font-semibold px-2">
                  Reply
                </button>
              </div>
            )}

            {repliesOf(c.id).length > 0 && (
              <div className="ml-4 mt-2 space-y-2 border-l border-neutral-800 pl-3">
                {repliesOf(c.id).map((r) => (
                  <div key={r.id}>
                    <span className="text-xs font-semibold">{r.authorName}</span>
                    <p className="text-xs text-neutral-300">{r.content}</p>
                    <div className="flex items-center gap-3 mt-1 text-[11px] text-neutral-500">
                      <button onClick={() => vote(r.id, 1)} className={`flex items-center gap-1 ${r.myVote === 1 ? "text-green-500" : "hover:text-white"}`}>
                        <ThumbsUp size={12} /> {r.likeCount}
                      </button>
                      <button onClick={() => vote(r.id, -1)} className={`flex items-center gap-1 ${r.myVote === -1 ? "text-red-500" : "hover:text-white"}`}>
                        <ThumbsDown size={12} /> {r.dislikeCount}
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        ))}
        {topLevel.length === 0 && <p className="text-xs text-neutral-600">No comments yet.</p>}
        {topLevel.length > visibleCount && (
          <button
            onClick={() => setVisibleCount((v) => v + 10)}
            className="text-xs text-red-500 font-semibold hover:text-red-400"
          >
            Show more comments ({topLevel.length - visibleCount} remaining)
          </button>
        )}
      </div>
    </div>
  );
}
