import { useState, useEffect, useCallback } from 'react';
import { getComments, createComment, TrackComment, CommentError } from '../services/commentService';
import { CommentForm } from './CommentForm';
import { CommentItem } from './CommentItem';
import { Button } from '@/components/ui/button';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { useToast } from '@/hooks/useToast';
import { Loader2, MessageSquare } from 'lucide-react';
import { cn } from '@/lib/utils';

interface CommentSectionProps {
  trackId: number;
  className?: string;
}

/**
 * CommentSection Component
 * T0290: Composant principal pour afficher et gérer les commentaires d'un track
 */
export function CommentSection({ trackId, className }: CommentSectionProps) {
  const [comments, setComments] = useState<TrackComment[]>([]);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(false);
  const limit = 20;
  const { toast } = useToast();

  const loadComments = useCallback(async () => {
    setLoading(true);
    try {
      const data = await getComments(trackId, page, limit);
      if (page === 1) {
        setComments(data.comments);
      } else {
        setComments((prev) => [...prev, ...data.comments]);
      }
      setTotal(data.total);
      setHasMore(data.comments.length === limit && comments.length + data.comments.length < data.total);
    } catch (error) {
      console.error('Failed to load comments:', error);
      if (error instanceof CommentError) {
        toast.error(error.message);
      } else {
        toast.error('Impossible de charger les commentaires');
      }
    } finally {
      setLoading(false);
    }
  }, [trackId, page, limit, toast]);

  useEffect(() => {
    loadComments();
  }, [loadComments]);

  const handleNewComment = async (content: string, parentId?: number) => {
    try {
      const newComment = await createComment(trackId, content, parentId);
      if (parentId) {
        // Ajouter comme réponse au commentaire parent
        setComments((prev) =>
          prev.map((c) =>
            c.id === parentId
              ? { ...c, replies: [...(c.replies || []), newComment] }
              : c
          )
        );
      } else {
        // Ajouter comme nouveau commentaire en haut de la liste
        setComments((prev) => [newComment, ...prev]);
        setTotal((prev) => prev + 1);
      }
      toast.success(parentId ? 'Réponse ajoutée' : 'Commentaire ajouté');
    } catch (error: any) {
      const errorMessage = error?.message || 'Impossible de créer le commentaire';
      toast.error(errorMessage);
      throw error;
    }
  };

  const handleLoadMore = () => {
    setPage((prev) => prev + 1);
  };

  const handleRefresh = () => {
    setPage(1);
    setComments([]);
  };

  return (
    <div className={cn('space-y-4', className)}>
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold">
          Commentaires {total > 0 && `(${total})`}
        </h3>
        {comments.length > 0 && (
          <Button variant="ghost" size="sm" onClick={handleRefresh} disabled={loading}>
            Actualiser
          </Button>
        )}
      </div>

      {/* Formulaire de commentaire */}
      <CommentForm onSubmit={handleNewComment} />

      {/* Liste des commentaires */}
      {loading && comments.length === 0 ? (
        <div className="flex items-center justify-center py-8">
          <LoadingSpinner />
        </div>
      ) : comments.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-12 text-center">
          <MessageSquare className="h-12 w-12 text-muted-foreground mb-4" />
          <p className="text-muted-foreground">Aucun commentaire pour le moment</p>
          <p className="text-sm text-muted-foreground mt-1">
            Soyez le premier à commenter ce track !
          </p>
        </div>
      ) : (
        <>
          <div className="space-y-4">
            {comments.map((comment) => (
              <CommentItem
                key={comment.id}
                comment={comment}
                trackId={trackId}
                onReply={handleNewComment}
                onUpdate={handleRefresh}
                onDelete={handleRefresh}
              />
            ))}
          </div>

          {/* Bouton charger plus */}
          {hasMore && (
            <div className="flex justify-center pt-4">
              <Button
                variant="outline"
                onClick={handleLoadMore}
                disabled={loading}
              >
                {loading ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    Chargement...
                  </>
                ) : (
                  'Charger plus de commentaires'
                )}
              </Button>
            </div>
          )}
        </>
      )}
    </div>
  );
}
