import { useParams, useNavigate } from 'react-router-dom';
import { useTicketDetail } from '@/hooks/useTicketDetail';

import { Card } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Loader } from '@/components/ui/Loader';
import { EmptyState } from '@/components/ui/EmptyState';
import { BackButton } from '@/components/ui/BackButton'; // Importation

import { TicketInfoWidget } from '@/components/widgets/TicketInfoWidget';
import { TicketChatWidget } from '@/components/widgets/TicketChatWidget';

export default function TicketDetail() {
  const { ticketId } = useParams<{ ticketId: string }>();
  const navigate = useNavigate();

  const { 
    ticket, messages, isLoading, error, isSending, 
    sendMessage, currentUser 
  } = useTicketDetail(ticketId);

  if (isLoading) return <div className="py-20"><Loader /></div>;
  
  if (error || !ticket) {
    return (
      <div className="max-w-4xl mx-auto py-12 px-4">
        <Card className="text-center py-12">
          <EmptyState message={error || "Ticket introuvable."} className="text-red-500 mb-6 not-italic font-medium" />
          <Button onClick={() => navigate('/support')} variant="outline">
            Retour au Centre de Support
          </Button>
        </Card>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto py-8 px-4 space-y-6">
      
      {/* BOUTON DE RETOUR EXTRAIT */}
      <BackButton to="/support" label="Retour au Centre de Support" />

      {/* WIDGETS */}
      <TicketInfoWidget ticket={ticket} />

      <TicketChatWidget 
        messages={messages}
        currentUserId={currentUser?.id}
        isSending={isSending}
        onSendMessage={sendMessage}
      />

    </div>
  );
}