import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/FormField';
import { useToast } from '@/hooks/useToast';
import { Send, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';

interface CommentFormProps {
  onSubmit: (content: string, parentId?: number) => Promise<void>;
  parentId?: number;
  initialContent?: string;
  onCancel?: () => void;
  placeholder?: string;
  className?: string;
}

/**
 * CommentForm Component
 * T0290: Formulaire pour créer ou éditer un commentaire
 */
export function CommentForm({
  onSubmit,
  parentId,
  initialContent = '',
  onCancel,
  placeholder = 'Écrivez un commentaire...',
  className,
}: CommentFormProps) {
  const [content, setContent] = useState(initialContent);
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!content.trim()) {
      toast.error('Le commentaire ne peut pas être vide');
      return;
    }

    if (content.length > 5000) {
      toast.error('Le commentaire ne peut pas dépasser 5000 caractères');
      return;
    }

    setLoading(true);
    try {
      await onSubmit(content.trim(), parentId);
      setContent('');
      if (onCancel) {
        onCancel();
      }
    } catch (error: any) {
      const errorMessage = error?.message || 'Impossible de créer le commentaire';
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    setContent('');
    if (onCancel) {
      onCancel();
    }
  };

  return (
    <form onSubmit={handleSubmit} className={cn('space-y-2', className)}>
      <Textarea
        value={content}
        onChange={(e) => setContent(e.target.value)}
        placeholder={placeholder}
        rows={3}
        disabled={loading}
        className="resize-none"
        maxLength={5000}
      />
      <div className="flex items-center justify-between">
        <span className="text-xs text-muted-foreground">
          {content.length}/5000
        </span>
        <div className="flex items-center gap-2">
          {onCancel && (
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={handleCancel}
              disabled={loading}
            >
              Annuler
            </Button>
          )}
          <Button
            type="submit"
            size="sm"
            disabled={loading || !content.trim()}
          >
            {loading ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Envoi...
              </>
            ) : (
              <>
                <Send className="w-4 h-4 mr-2" />
                {parentId ? 'Répondre' : 'Commenter'}
              </>
            )}
          </Button>
        </div>
      </div>
    </form>
  );
}
