"use client";
import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";

type Comment = {
  id: string;
  authorName: string;
  content: string;
  parentId: string | null;
  createdAt: string;
};

export default function BlogComments({ slug }: { slug: 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 [loaded, setLoaded] = useState(false);

  async function load() {
    const res = await fetch(`/api/blog/${slug}/comments`);
    setComments(await res.json());
    setLoaded(true);
  }

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

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

  const topLevel = comments.filter((c) => !c.parentId);
  const repliesOf = (id: string) => comments.filter((c) => c.parentId === id);

  return (
    <div>
      <h2 className="text-lg font-semibold mb-4">Comments ({comments.length})</h2>

      <div className="flex gap-2 mb-6">
        <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-4 py-2.5 text-sm outline-none focus:border-red-600"
          onKeyDown={(e) => e.key === "Enter" && submit(newComment)}
        />
        <button onClick={() => submit(newComment)} className="btn-primary px-5 py-2.5 text-sm">
          Post
        </button>
      </div>

      <div className="space-y-4">
        {loaded && topLevel.length === 0 && (
          <p className="text-sm text-neutral-500">Be the first to comment.</p>
        )}
        {topLevel.map((c) => (
          <div key={c.id}>
            <div className="flex gap-2.5">
              <div className="w-8 h-8 rounded-full bg-neutral-700 flex items-center justify-center text-xs font-bold shrink-0">
                {c.authorName[0]?.toUpperCase() || "?"}
              </div>
              <div className="flex-1">
                <p className="text-sm">
                  <span className="font-semibold">{c.authorName}</span>{" "}
                  <span className="text-neutral-300">{c.content}</span>
                </p>
                <div className="flex items-center gap-3 mt-1">
                  <span className="text-xs text-neutral-600">{new Date(c.createdAt).toLocaleDateString()}</span>
                  <button
                    onClick={() => setReplyingTo(replyingTo === c.id ? null : c.id)}
                    className="text-xs text-neutral-500 hover:text-white"
                  >
                    Reply
                  </button>
                </div>

                {replyingTo === c.id && (
                  <div className="flex gap-2 mt-2">
                    <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="mt-3 space-y-3 pl-3 border-l border-neutral-800">
                    {repliesOf(c.id).map((r) => (
                      <div key={r.id} className="flex gap-2.5">
                        <div className="w-6 h-6 rounded-full bg-neutral-700 flex items-center justify-center text-[10px] font-bold shrink-0">
                          {r.authorName[0]?.toUpperCase() || "?"}
                        </div>
                        <div>
                          <p className="text-sm">
                            <span className="font-semibold">{r.authorName}</span>{" "}
                            <span className="text-neutral-300">{r.content}</span>
                          </p>
                          <span className="text-xs text-neutral-600">{new Date(r.createdAt).toLocaleDateString()}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
