"use client";

import { useEffect, useRef } from "react";
import { useSearchParams } from "next/navigation";
import { CommentForm } from "./comment-form";
import { CommentItem } from "./comment-item";

interface Comment {
  id: string;
  content: string;
  attachments?: string[];
  createdAt: string | Date;
  updatedAt?: string | Date;
  author: {
    id: string;
    name?: string | null;
    email: string;
    image?: string | null;
  };
}

interface TaskCommentsSectionProps {
  taskId: string;
  comments: Comment[];
}

export const TaskCommentsSection = ({ taskId, comments }: TaskCommentsSectionProps) => {
  const searchParams = useSearchParams();
  const commentToScrollTo = searchParams.get("comment");
  const commentRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});

  // Scroll to specific comment if coming from notification
  useEffect(() => {
    if (commentToScrollTo && commentRefs.current[commentToScrollTo]) {
      const element = commentRefs.current[commentToScrollTo];
      element.scrollIntoView({ 
        behavior: "smooth", 
        block: "center" 
      });
      
      // Highlight the comment briefly
      element.classList.add("ring-2", "ring-blue-500", "ring-opacity-50");
      setTimeout(() => {
        element.classList.remove("ring-2", "ring-blue-500", "ring-opacity-50");
      }, 3000);
    }
  }, [commentToScrollTo, comments]);

  return (
    <div className="space-y-6">
      <div className="space-y-4">
        <h3 className="text-lg font-semibold">Comments ({comments.length})</h3>
        
        <CommentForm taskId={taskId} />
        
        {comments.length > 0 && (
          <div className="space-y-4">
            {comments.map((comment) => (
              <div
                key={comment.id}
                ref={(el) => {
                  commentRefs.current[comment.id] = el;
                }}
                className="transition-all duration-300"
              >
                <CommentItem comment={comment} taskId={taskId} />
              </div>
            ))}
          </div>
        )}
        
        {comments.length === 0 && (
          <div className="text-center py-8 text-gray-500">
            No comments yet. Be the first to comment!
          </div>
        )}
      </div>
    </div>
  );
}; 