"use client";
import React, { useEffect, useRef, useState } from "react";
import CommentForm from "@/components/comment/comment-form";
import CommentList from "@/components/comment/comment-list";
import { Comment, CommentNode } from "@/server/db/schema";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { useComments } from "@/lib/hooks/use-comments-hook";

import { SocketProvider, useSocket } from "../socket-context";
import { JOIN_ROOM_EVENT } from "@/server/socket/event-const";

function CommentSection({ articleId }: { articleId: string }) {
  const { comments } = useComments(articleId);
  const [replyComment, setReplyComment] = useState<CommentNode | undefined>();
  const commentRefs = useRef<Map<string, HTMLDivElement | null>>(new Map());
  const { socket } = useSocket();
  useEffect(() => {
    if (!socket) return;
    console.log("RERUN COMMENT SECTION");

    socket.emit(JOIN_ROOM_EVENT, articleId);
    return () => {
      socket.disconnect();
    };
  }, [socket]);

  return (
    <div className="space-y-4">
      <div className="sticky top-0 z-50 bg-background pt-4">
        <CommentForm
          articleId={articleId}
          parentComment={replyComment}
          removeReplyComment={() => setReplyComment(undefined)}
          commentRefs={commentRefs}
        />
      </div>

      <div className="flex items-center justify-between gap-4">
        <div className="flex items-center gap-2">
          <h4 className="text-lg font-medium">Kommentare </h4>
          <Badge>{comments?.length}</Badge>
        </div>
        <Button size={"sm"} variant={"outline"}>
          <span>Sort</span>
        </Button>
      </div>

      {comments && (
        <CommentList
          comments={comments}
          commentRefs={commentRefs}
          setReplyComment={setReplyComment}
        />
      )}
    </div>
  );
}

export default CommentSection;
