import { useState } from 'react';
import { TrackComment, updateComment, deleteComment, getReplies } from '../services/commentService';
import { CommentForm } from './CommentForm';
import { Button } from '@/components/ui/button';
import { useToast } from '@/hooks/useToast';
import { useAuthStore } from '@/stores/auth';
import { Edit2, Trash2, Reply, MoreVertical, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';

interface CommentItemProps {
  comment: TrackComment;
  trackId: number;
  onReply?: (content: string, parentId: number) => Promise<void>;
  onUpdate?: () => void;
  onDelete?: () => void;
  depth?: number;
  className?: string;
}

/**
 * CommentItem Component
 * T0290: Composant pour afficher un commentaire avec ses réponses
 */
export function CommentItem({
  comment,
  trackId,
  onReply,
  onUpdate,
  onDelete,
  depth = 0,
  className,
}: CommentItemProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [isReplying, setIsReplying] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [replies, setReplies] = useState<TrackComment[]>(comment.replies || []);
  const [showReplies, setShowReplies] = useState(depth === 0 && replies.length > 0);
  const [loadingReplies, setLoadingReplies] = useState(false);
  const { toast } = useToast();
  const { user } = useAuthStore();

  const isOwner = user?.id === comment.user_id;
  const maxDepth = 3; // Limite de profondeur pour les réponses imbriquées

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);

    if (diffInSeconds < 60) {
      return 'À l\'instant';
    }
    if (diffInSeconds < 3600) {
      const minutes = Math.floor(diffInSeconds / 60);
      return `Il y a ${minutes} minute${minutes > 1 ? 's' : ''}`;
    }
    if (diffInSeconds < 86400) {
      const hours = Math.floor(diffInSeconds / 3600);
      return `Il y a ${hours} heure${hours > 1 ? 's' : ''}`;
    }
    if (diffInSeconds < 604800) {
      const days = Math.floor(diffInSeconds / 86400);
      return `Il y a ${days} jour${days > 1 ? 's' : ''}`;
    }
    return date.toLocaleDateString('fr-FR', {
      day: 'numeric',
      month: 'short',
      year: date.getFullYear() !== now.getFullYear() ? 'numeric' : undefined,
    });
  };

  const handleUpdate = async (content: string) => {
    try {
      await updateComment(comment.id, content);
      setIsEditing(false);
      if (onUpdate) {
        onUpdate();
      }
      toast.success('Commentaire mis à jour');
    } catch (error: any) {
      const errorMessage = error?.message || 'Impossible de mettre à jour le commentaire';
      toast.error(errorMessage);
      throw error;
    }
  };

  const handleDelete = async () => {
    if (!confirm('Êtes-vous sûr de vouloir supprimer ce commentaire ?')) {
      return;
    }

    setIsDeleting(true);
    try {
      await deleteComment(comment.id);
      if (onDelete) {
        onDelete();
      }
      toast.success('Commentaire supprimé');
    } catch (error: any) {
      const errorMessage = error?.message || 'Impossible de supprimer le commentaire';
      toast.error(errorMessage);
    } finally {
      setIsDeleting(false);
    }
  };

  const handleReply = async (content: string, parentId: number) => {
    if (onReply) {
      try {
        await onReply(content, parentId);
        setIsReplying(false);
        // Recharger les réponses
        if (showReplies) {
          loadReplies();
        } else {
          setShowReplies(true);
        }
      } catch (error) {
        throw error;
      }
    }
  };

  const loadReplies = async () => {
    if (replies.length > 0 && showReplies) {
      return; // Déjà chargées
    }

    setLoadingReplies(true);
    try {
      const data = await getReplies(comment.id, 1, 20);
      setReplies(data.replies);
      setShowReplies(true);
    } catch (error) {
      console.error('Failed to load replies:', error);
    } finally {
      setLoadingReplies(false);
    }
  };

  const toggleReplies = () => {
    if (!showReplies && replies.length === 0) {
      loadReplies();
    } else {
      setShowReplies(!showReplies);
    }
  };

  return (
    <div className={cn('space-y-2', className)}>
      <div className={cn('flex gap-3', depth > 0 && 'ml-8')}>
        {/* Avatar */}
        <div className="flex-shrink-0">
          <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary font-medium text-sm">
            {comment.user.username.charAt(0).toUpperCase()}
          </div>
        </div>

        {/* Contenu */}
        <div className="flex-1 min-w-0">
          <div className="bg-muted/50 rounded-lg p-3">
            {/* En-tête */}
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center gap-2">
                <span className="font-medium text-sm">{comment.user.username}</span>
                <span className="text-xs text-muted-foreground">
                  {formatDate(comment.created_at)}
                </span>
                {comment.is_edited && (
                  <span className="text-xs text-muted-foreground italic">
                    (modifié)
                  </span>
                )}
              </div>

              {/* Actions */}
              {isOwner && (
                <div className="flex items-center gap-1">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setIsEditing(true)}
                    className="h-6 px-2 text-xs"
                  >
                    <Edit2 className="h-3 w-3 mr-1" />
                    Modifier
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={handleDelete}
                    disabled={isDeleting}
                    className="h-6 px-2 text-xs text-destructive hover:text-destructive"
                  >
                    {isDeleting ? (
                      <Loader2 className="h-3 w-3 mr-1 animate-spin" />
                    ) : (
                      <Trash2 className="h-3 w-3 mr-1" />
                    )}
                    Supprimer
                  </Button>
                </div>
              )}
            </div>

            {/* Contenu du commentaire */}
            {isEditing ? (
              <CommentForm
                onSubmit={handleUpdate}
                initialContent={comment.content}
                onCancel={() => setIsEditing(false)}
                placeholder="Modifier le commentaire..."
              />
            ) : (
              <div className="text-sm whitespace-pre-wrap break-words">
                {comment.content}
              </div>
            )}

            {/* Actions */}
            {!isEditing && depth < maxDepth && (
              <div className="flex items-center gap-2 mt-2">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setIsReplying(!isReplying)}
                  className="h-7 text-xs"
                >
                  <Reply className="h-3 w-3 mr-1" />
                  Répondre
                </Button>
                {comment.replies && comment.replies.length > 0 && (
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={toggleReplies}
                    className="h-7 text-xs"
                    disabled={loadingReplies}
                  >
                    {loadingReplies ? (
                      <Loader2 className="h-3 w-3 mr-1 animate-spin" />
                    ) : (
                      <>
                        {showReplies ? 'Masquer' : 'Afficher'} {comment.replies.length} réponse
                        {comment.replies.length > 1 ? 's' : ''}
                      </>
                    )}
                  </Button>
                )}
              </div>
            )}
          </div>

          {/* Formulaire de réponse */}
          {isReplying && !isEditing && (
            <div className="mt-2 ml-4">
              <CommentForm
                onSubmit={(content) => handleReply(content, comment.id)}
                parentId={comment.id}
                onCancel={() => setIsReplying(false)}
                placeholder="Écrivez une réponse..."
              />
            </div>
          )}

          {/* Réponses */}
          {showReplies && replies.length > 0 && (
            <div className="mt-2 space-y-2">
              {replies.map((reply) => (
                <CommentItem
                  key={reply.id}
                  comment={reply}
                  trackId={trackId}
                  onReply={onReply}
                  onUpdate={onUpdate}
                  onDelete={onDelete}
                  depth={depth + 1}
                />
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
