'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { api, apiPaths } from '@/lib/api';
import { useAuthGuard } from '@/lib/useAuthGuard';

type Ticket = {
  id: number;
  ticket_number: string;
  title: string;
  description: string;
  type?: string;
  type_label?: string;
  order_number?: string;
  status: string;
  admin_reply?: string;
  created_at?: string;
};

export default function SupportTicketsPage() {
  const { checked, authenticated } = useAuthGuard();
  const router = useRouter();
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!authenticated) return;
    api.get<Ticket[]>(apiPaths.supportTickets.list).then((res) => {
      if (res.key === 'success' && res.data) setTickets(res.data as Ticket[]);
      setLoading(false);
    }).catch(() => setLoading(false));
  }, [authenticated]);

  if (!checked) return null;

  const handleTicketClick = (id: number) => { router.push(`/support-tickets/${id}`); };
  const handleCreateTicket = () => { router.push('/support-tickets/create'); };

  const getStatusLabel = (status: string) => {
    switch (status) {
      case 'pending': return 'معلقة';
      case 'resolved': return 'تم الحل';
      case 'closed': return 'مغلقة';
      default: return status;
    }
  };

  const getStatusStyle = (status: string) => {
    switch (status) {
      case 'pending': return 'bg-[#F7D612]/20 text-[#B8A00A]';
      case 'resolved': return 'bg-[#19396A]/10 text-[#19396A]';
      case 'closed': return 'bg-gray-100 text-gray-600';
      default: return 'bg-gray-100 text-gray-600';
    }
  };

  return (
    <div dir="rtl" className="flex flex-col flex-1 bg-[#F6F6F8]">
      <main className="max-w-6xl mx-auto px-6 py-12 flex-1 w-full">
        <div className="flex items-center justify-between mb-8">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 mb-2">تذاكر الدعم</h1>
            <p className="text-gray-600">إدارة ومتابعة تذاكر الدعم الخاصة بك</p>
          </div>
          <button
            onClick={handleCreateTicket}
            className="flex items-center gap-2 bg-[#19396A] text-white px-6 py-3 rounded-2xl hover:bg-[#164278] transition-colors cursor-pointer whitespace-nowrap font-semibold"
          >
            <i className="ri-add-line text-xl"></i>
            <span>إضافة تذكرة جديدة</span>
          </button>
        </div>

        {loading ? (
          <div className="flex justify-center py-16">
            <div className="w-12 h-12 border-4 border-[#19396A] border-t-transparent rounded-full animate-spin"></div>
          </div>
        ) : tickets.length === 0 ? (
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-12 text-center">
            <i className="ri-ticket-line text-6xl text-gray-300 mb-4 block"></i>
            <h2 className="text-xl font-bold text-gray-900 mb-2">لا توجد تذاكر دعم حالياً</h2>
            <p className="text-gray-600 mb-6">لم تقم بإنشاء أي تذاكر دعم بعد</p>
            <button onClick={handleCreateTicket} className="bg-[#19396A] text-white px-8 py-3 rounded-2xl hover:bg-[#164278] transition-colors cursor-pointer whitespace-nowrap font-semibold">
              إضافة تذكرة جديدة
            </button>
          </div>
        ) : (
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50 border-b border-gray-100">
                  <tr>
                    <th className="px-6 py-4 text-right text-sm font-bold text-gray-900">رقم التذكرة</th>
                    <th className="px-6 py-4 text-right text-sm font-bold text-gray-900">العنوان</th>
                    <th className="px-6 py-4 text-right text-sm font-bold text-gray-900">النوع</th>
                    <th className="px-6 py-4 text-right text-sm font-bold text-gray-900">تاريخ الإنشاء</th>
                    <th className="px-6 py-4 text-right text-sm font-bold text-gray-900">رقم الطلب المرتبط</th>
                    <th className="px-6 py-4 text-right text-sm font-bold text-gray-900">الحالة</th>
                    <th className="px-6 py-4 text-right text-sm font-bold text-gray-900">الإجراءات</th>
                  </tr>
                </thead>
                <tbody>
                  {tickets.map((ticket, index) => (
                    <tr key={ticket.id} className={`${index !== tickets.length - 1 ? 'border-b border-gray-100' : ''} hover:bg-gray-50 transition-colors`}>
                      <td className="px-6 py-4">
                        <span className="font-semibold text-[#19396A]">{ticket.ticket_number}</span>
                      </td>
                      <td className="px-6 py-4 text-gray-700 text-sm">{ticket.title}</td>
                      <td className="px-6 py-4 text-gray-700 text-sm">{ticket.type_label ?? ticket.type ?? '—'}</td>
                      <td className="px-6 py-4 text-gray-700 text-sm">
                        {ticket.created_at ? new Date(ticket.created_at).toLocaleDateString('ar') : '—'}
                      </td>
                      <td className="px-6 py-4">
                        <span className="text-[#19396A] font-semibold">{ticket.order_number || '—'}</span>
                      </td>
                      <td className="px-6 py-4">
                        <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-semibold whitespace-nowrap ${getStatusStyle(ticket.status)}`}>
                          {getStatusLabel(ticket.status)}
                        </span>
                      </td>
                      <td className="px-6 py-4">
                        <button onClick={() => handleTicketClick(ticket.id)} className="text-[#19396A] hover:bg-[#19396A]/10 px-4 py-2 rounded-lg transition-colors cursor-pointer whitespace-nowrap font-semibold">
                          عرض التفاصيل
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}
