
import React, { useState } from 'react';
import { Helmet } from 'react-helmet';
import { useParams, useNavigate } from 'react-router-dom';
import { ArrowLeft, Send, User, Clock, AlertCircle } from 'lucide-react';
import StatusBadge from '@/components/StatusBadget';
import { mockTickets } from '@/data/mockData';
import { toast } from '@/components/ui/use-toast';
import { motion } from 'framer-motion';

const TicketDetailPage = () => {
   const { id } = useParams();
   const navigate = useNavigate();
   const [ticket, setTicket] = useState(mockTickets.find(t => t.id === parseInt(id)));
   const [comment, setComment] = useState('');

   if (!ticket) return <div>Ticket non trouvé</div>;

   const handleAddComment = (e) => {
      e.preventDefault();
      if (!comment.trim()) return;

      const newComment = {
         id: Math.random(),
         user: 'Jean Dupont', // Current user
         date: new Date().toISOString().split('T')[0],
         text: comment
      };

      setTicket(prev => ({
         ...prev,
         comments: [...(prev.comments || []), newComment]
      }));
      setComment('');
      toast({ title: "Commentaire ajouté" });
   };

   const handleStatusChange = (e) => {
      const newStatus = e.target.value;
      setTicket(prev => ({ ...prev, status: newStatus }));
      toast({ title: "Statut mis à jour", description: `Nouveau statut: ${newStatus}` });
   };

   return (
      <>
         <Helmet>
            <title>{ticket.number} - Support</title>
         </Helmet>

         <div className="space-y-6 max-w-6xl mx-auto h-[calc(100vh-100px)] flex flex-col">
            <div className="flex-shrink-0">
               <button onClick={() => navigate('/tickets')} className="flex items-center gap-2 text-sm text-gray-500 hover:text-gray-900 mb-4">
                  <ArrowLeft className="w-4 h-4" /> Retour
               </button>

               <div className="flex justify-between items-start bg-white dark:bg-gray-950 p-6 rounded-2xl border border-gray-200 dark:border-gray-800 shadow-sm">
                  <div>
                     <div className="flex items-center gap-3 mb-2">
                        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">{ticket.number}</h1>
                        <StatusBadge status={ticket.status} />
                        <span className={`px-2 py-0.5 rounded text-xs font-bold uppercase ${ticket.priority === 'critical' ? 'bg-red-100 text-red-600' :
                              ticket.priority === 'high' ? 'bg-orange-100 text-orange-600' : 'bg-blue-100 text-blue-600'
                           }`}>
                           {ticket.priority}
                        </span>
                     </div>
                     <h2 className="text-lg font-medium">{ticket.subject}</h2>
                     <p className="text-gray-500 text-sm">Client: <span className="font-medium text-gray-900 dark:text-white">{ticket.client}</span></p>
                  </div>
                  <div className="flex flex-col items-end gap-2">
                     <select
                        value={ticket.status}
                        onChange={handleStatusChange}
                        className="px-3 py-2 rounded-xl border border-gray-200 bg-gray-50 text-sm font-medium focus:ring-2 focus:ring-[#941403]"
                     >
                        <option value="open">Ouvert</option>
                        <option value="in-progress">En cours</option>
                        <option value="pending">En attente</option>
                        <option value="resolved">Résolu</option>
                        <option value="closed">Fermé</option>
                     </select>
                     <div className="text-xs text-gray-500 flex items-center gap-1">
                        <Clock className="w-3 h-3" /> Ouvert le {ticket.openDate}
                     </div>
                  </div>
               </div>
            </div>

            <div className="flex-1 grid grid-cols-3 gap-6 min-h-0">
               {/* Conversation Column */}
               <div className="col-span-2 bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl flex flex-col overflow-hidden">
                  <div className="p-4 border-b border-gray-100 bg-gray-50/50 font-medium">Fil de discussion</div>

                  <div className="flex-1 overflow-y-auto p-6 space-y-6">
                     {/* Original Description */}
                     <div className="flex gap-4">
                        <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center shrink-0 text-blue-600 font-bold">C</div>
                        <div>
                           <div className="flex items-baseline gap-2 mb-1">
                              <span className="font-bold text-sm">{ticket.client}</span>
                              <span className="text-xs text-gray-500">{ticket.openDate}</span>
                           </div>
                           <div className="bg-gray-100 dark:bg-gray-900 p-4 rounded-2xl rounded-tl-none text-sm leading-relaxed">
                              {ticket.description}
                           </div>
                        </div>
                     </div>

                     {/* Comments */}
                     {ticket.comments?.map((c, i) => (
                        <motion.div
                           key={i}
                           initial={{ opacity: 0, y: 10 }}
                           animate={{ opacity: 1, y: 0 }}
                           className="flex gap-4"
                        >
                           <div className="w-10 h-10 rounded-full bg-[#941403] flex items-center justify-center shrink-0 text-white font-bold">
                              {c.user.charAt(0)}
                           </div>
                           <div>
                              <div className="flex items-baseline gap-2 mb-1">
                                 <span className="font-bold text-sm">{c.user}</span>
                                 <span className="text-xs text-gray-500">{c.date}</span>
                              </div>
                              <div className="bg-red-50 dark:bg-red-900/10 border border-red-100 dark:border-red-900/30 p-4 rounded-2xl rounded-tl-none text-sm leading-relaxed">
                                 {c.text}
                              </div>
                           </div>
                        </motion.div>
                     ))}
                  </div>

                  <div className="p-4 border-t border-gray-100 dark:border-gray-800 bg-gray-50 dark:bg-gray-900/30">
                     <form onSubmit={handleAddComment} className="flex gap-3">
                        <input
                           type="text"
                           value={comment}
                           onChange={(e) => setComment(e.target.value)}
                           placeholder="Écrire une réponse interne ou publique..."
                           className="flex-1 px-4 py-3 rounded-xl border border-gray-200 focus:ring-2 focus:ring-[#941403] outline-none text-sm"
                        />
                        <button
                           type="submit"
                           disabled={!comment.trim()}
                           className="p-3 bg-[#941403] text-white rounded-xl hover:bg-[#7a1002] disabled:opacity-50 transition-colors"
                        >
                           <Send className="w-5 h-5" />
                        </button>
                     </form>
                  </div>
               </div>

               {/* Sidebar Info */}
               <div className="col-span-1 space-y-6">
                  <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-6">
                     <h3 className="text-sm font-bold uppercase text-gray-400 mb-4">SLA</h3>
                     <div className="space-y-4">
                        <div>
                           <div className="flex justify-between text-sm mb-1">
                              <span>Temps réponse</span>
                              <span className="font-medium text-green-600">OK</span>
                           </div>
                           <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
                              <div className="h-full bg-green-500 w-[80%]" />
                           </div>
                        </div>
                        <div>
                           <div className="flex justify-between text-sm mb-1">
                              <span>Résolution</span>
                              <span className="font-medium text-yellow-600">Attention</span>
                           </div>
                           <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
                              <div className="h-full bg-yellow-500 w-[90%]" />
                           </div>
                        </div>
                     </div>
                  </div>

                  <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-6">
                     <h3 className="text-sm font-bold uppercase text-gray-400 mb-4">Assigné à</h3>
                     <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center">
                           <User className="w-5 h-5 text-gray-500" />
                        </div>
                        <div>
                           <p className="font-medium">{ticket.assignedTo}</p>
                           <p className="text-xs text-gray-500">Support N2</p>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </>
   );
};

export default TicketDetailPage;
