'use client';

import { useState, useEffect } from "react";
import CommentForm from "./CommentForm";
import CommentList from "./CommentList";
import ReplyModal from "./ReplyModal";
import { Users, MessageSquare, Shield, Clock } from 'lucide-react';

export default function CommentSection({ 
  article, 
  initialComments = [], 
  initialReplies = [] 
}) {
  const [comments, setComments] = useState(initialComments);
  const [replies, setReplies] = useState(initialReplies);
  const [replyingTo, setReplyingTo] = useState(null);
  const [showReplyModal, setShowReplyModal] = useState(false);

  const formatDate = (dateString) => {
    const options = { year: 'numeric', month: 'long', day: 'numeric' };
    return new Date(dateString).toLocaleDateString(undefined, options);
  };

  const refreshComments = async () => {
    try {
      const response = await fetch(`/api/frontend/comments?article_id=${article.id}`);
      const data = await response.json();
      if (data.success) {
        setComments(data.data);
        // Update approved count
        const approvedCount = data.data.filter(comment => 
          comment.status === 'approved' || comment.status === 1
        ).length;
        setApprovedCommentsCount(approvedCount);
      }
    } catch (error) {
      console.error('Error refreshing comments:', error);
    }
  };

  const refreshReplies = async () => {
    try {
      const response = await fetch(`/api/frontend/replies?article_id=${article.id}`);
      const data = await response.json();
      if (data.success) {
        setReplies(data.data);
      }
    } catch (error) {
      console.error('Error refreshing replies:', error);
    }
  };

  const openReplyModal = (item) => {
    setReplyingTo(item);
    setShowReplyModal(true);
  };

  const closeReplyModal = () => {
    setShowReplyModal(false);
    setReplyingTo(null);
  };

  const countTotalReplies = (commentId) => {
    let count = 0;
    
    const firstLevel = replies.filter(reply => 
      String(reply.parent_comment_id) === String(commentId) && 
      !reply.parent_reply_id &&
      (reply.status === 'approved' || reply.status === 1) &&
      String(reply.article_id) === String(article.id)
    );
    count += firstLevel.length;
    
    const countNested = (replyId) => {
      const nested = replies.filter(reply => 
        reply.parent_reply_id === replyId && 
        (reply.status === 'approved' || reply.status === 1) &&
        String(reply.article_id) === String(article.id)
      );
      count += nested.length;
      nested.forEach(reply => countNested(reply.reply_id));
    };
    
    firstLevel.forEach(reply => countNested(reply.reply_id));
    
    return count;
  };

  const renderReplies = (parentId, isComment = false, depth = 0) => {
    let filteredReplies = replies.filter(reply => 
        String(reply.article_id) === String(article.id) &&
        (isComment 
        ? String(reply.parent_comment_id) === String(parentId) && !reply.parent_reply_id
        : reply.parent_reply_id === parentId)
    );

    if (filteredReplies.length === 0) return null;
    const maxDepth = 5;
    if (depth >= maxDepth) return null;

    return (
        <div 
        className={`mt-4 pl-6 ${depth > 0 ? 'border-l-2 border-teal-300' : ''}`}
        style={{ marginLeft: `${depth * 1}rem` }}
        >
        {filteredReplies.map(reply => (
            <div key={reply.reply_id} className="mt-4 bg-linear-to-r from-teal-50/50 to-blue-50/50 p-4 rounded-xl border border-teal-100/50">
            <div className="flex justify-between items-start">
                <div className="flex items-center gap-3">
                <div className="bg-linear-to-r from-teal-600 to-blue-500 text-white w-8 h-8 rounded-full flex items-center justify-center font-semibold text-sm shadow-sm">
                    {reply.first_name?.charAt(0)}{reply.last_name?.charAt(0)}
                </div>
                <div>
                    <h5 className="font-semibold text-gray-800">
                    {reply.first_name} {reply.last_name}
                    </h5>
                    <span className="text-xs text-gray-500">
                    replied on {formatDate(reply.created_at)}
                    </span>
                </div>
                </div>
                <button 
                onClick={() => openReplyModal(reply)}
                className="flex items-center gap-1 text-teal-600 hover:text-teal-700 transition-colors text-sm bg-white/50 px-2 py-1 rounded-lg border border-teal-100 hover:border-teal-200"
                >
                ↩ Reply
                </button>
            </div>
            <p className="mt-2 text-gray-700 pl-11">{reply.comment}</p>
            {renderReplies(reply.reply_id, false, depth + 1)}
            </div>
        ))}
        </div>
    );
    };

  return (
    <div className="py-16">

      <div className="bg-linear-to-r from-teal-50/50 to-blue-50/50 rounded-3xl p-8 md:p-12 border border-teal-100 shadow-lg">
        {/* Header */}
        <div className="text-center mb-12">
          <div className="inline-flex items-center gap-2 bg-white/80 backdrop-blur-sm text-teal-700 px-6 py-3 rounded-full text-sm font-semibold mb-6">
            <MessageSquare className="w-5 h-5" />
            Join the Conversation
          </div>
          
          <h2 className="text-4xl font-bold text-gray-900 mb-4">
            Share Your Thoughts
          </h2>
          <p className="text-gray-600 text-lg max-w-2xl mx-auto">
            Engage with our community of students and education experts. Your insights matter!
          </p>
        </div>

        {/* Comment Form */}
        <CommentForm 
          article={article}
          onCommentSubmitted={refreshComments}
        />

        {/* Comment List */}
        <CommentList 
          comments={comments}
          article={article}
          countTotalReplies={countTotalReplies}
          renderReplies={renderReplies}
          formatDate={formatDate}
          onReplyClick={openReplyModal}
        />
      </div>

      {/* Reply Modal */}
      <ReplyModal 
        isOpen={showReplyModal}
        onClose={closeReplyModal}
        replyingTo={replyingTo}
        article={article}
        onReplySubmitted={() => {
          closeReplyModal();
          refreshReplies();
        }}
      />
    </div>
  );
}