import React, { useState } from 'react';
import { useAuth } from '../../../contexts/AuthContext';
import { useComments, useCreateComment } from '../../../queries/comments';
import { Button } from '../../ui/button';
import { Textarea } from '../../ui/textarea';
import { Card, CardContent } from '../../ui/card';
import { CommentItem } from './CommentItem';
import { usePostHog } from '@posthog/react';

interface CommentSectionProps {
  articleId?: string;
  liveBlogId?: string;
}

export function CommentSection({ articleId, liveBlogId }: CommentSectionProps) {
  const { isAuthenticated } = useAuth();
  const [newComment, setNewComment] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const posthog = usePostHog();
  
  const { data: commentsData, isLoading } = useComments({
    articleId,
    liveBlogId,
    limit: 50,
  });
  
  const createCommentMutation = useCreateComment();
  
  const comments = commentsData?.data || [];
  
  const handleSubmitComment = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!newComment.trim() || !isAuthenticated) return;

    setIsSubmitting(true);
    try {
      await createCommentMutation.mutateAsync({
        content: newComment,
        articleId,
        liveBlogId,
      });
      posthog.capture('comment_submitted', {
        article_id: articleId,
        live_blog_id: liveBlogId,
        target_type: liveBlogId ? 'live_blog' : 'article',
        comment_length: newComment.trim().length,
      });
      setNewComment('');
    } catch (error) {
      console.error('Failed to post comment:', error);
    } finally {
      setIsSubmitting(false);
    }
  };
  
  return (
    <div className="mt-12 pt-8 border-t">
      <h2 className="text-2xl font-bold mb-6">Коментари</h2>
      
      {isAuthenticated ? (
        <Card className="mb-8">
          <CardContent className="pt-6">
            <form onSubmit={handleSubmitComment}>
              <Textarea
                placeholder="Што мислите за овој напис?"
                value={newComment}
                onChange={(e) => setNewComment(e.target.value)}
                className="min-h-[100px] mb-4"
                disabled={isSubmitting}
              />
              <div className="flex justify-end">
                <Button 
                  type="submit" 
                  disabled={!newComment.trim() || isSubmitting}
                >
                  {isSubmitting ? 'Поставување...' : 'Постави коментар'}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      ) : (
        <Card className="mb-8">
          <CardContent className="pt-6 text-center">
            <p className="text-muted-foreground mb-4">
              Најавете се за да можете да коментирате
            </p>
            <Button asChild>
              <a href="/auth">Најави се</a>
            </Button>
          </CardContent>
        </Card>
      )}
      
      {isLoading ? (
        <div className="text-center py-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
          <p className="mt-2 text-sm text-muted-foreground">Вчитување коментари...</p>
        </div>
      ) : comments.length === 0 ? (
        <Card>
          <CardContent className="pt-6 text-center">
            <p className="text-muted-foreground">
              Сè уште нема коментари. Бидете првиот што ќе коментира!
            </p>
          </CardContent>
        </Card>
       ) : (
        <div className="space-y-6">
          {comments.map((comment) => (
            <CommentItem
              key={comment.id}
              comment={comment}
              articleId={articleId}
              liveBlogId={liveBlogId}
            />
          ))}
        </div>
      )}
    </div>
  );
}