import React, { useState } from 'react';
import type { TicketMessage } from '@/types/Message';
import { Card, CardContent, CardHeader } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { EmptyState } from '@/components/ui/EmptyState';
import { MessageBubble } from '@/components/ui/MessageBubble';

interface TicketChatWidgetProps {
  messages: TicketMessage[];
  currentUserId?: string;
  isSending: boolean;
  onSendMessage: (content: string) => Promise<void>;
}

export const TicketChatWidget: React.FC<TicketChatWidgetProps> = ({ 
  messages, 
  currentUserId, 
  isSending, 
  onSendMessage 
}) => {
  const [newMessage, setNewMessage] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newMessage.trim()) return;

    try {
      await onSendMessage(newMessage);
      setNewMessage(''); // Vide l'input uniquement si l'envoi réussit
    } catch {
      alert("Erreur lors de l'envoi.");
    }
  };

  return (
    <Card className="h-125">
      <CardHeader>
        <h2 className="text-sm font-semibold text-slate-800">Échanges chiffrés</h2>
      </CardHeader>

      {/* Zone des messages */}
      <CardContent className="flex-1 overflow-y-auto p-6 space-y-6">
        {messages.length === 0 ? (
          <EmptyState message="Aucun message pour l'instant. Démarrez la conversation ci-dessous." />
        ) : (
          messages.map((msg) => (
            <MessageBubble key={msg.id} message={msg} currentUserId={currentUserId} />
          ))
        )}
      </CardContent>

      {/* Zone de saisie avec notre composant UI */}
      <form onSubmit={handleSubmit} className="p-4 flex items-start space-x-3">
        <div className="flex-1">
          <Input
            value={newMessage}
            onChange={(e) => setNewMessage(e.target.value)}
            placeholder="Écrivez votre message..."
          />
        </div>
        <Button
          type="submit"
          isLoading={isSending}
          disabled={isSending || !newMessage.trim()}
          className="px-6"
        >
          Envoyer
        </Button>
      </form>
    </Card>
  );
};