"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { MessageCircle } from "lucide-react";
import TicketConversation from "@/components/TicketConversation";
import { usePageTitle } from "@/hooks/usePageTitle";

type Ticket = {
  id: string;
  org_id: string;
  subject: string;
  status: "open" | "waiting_client" | "waiting_staff" | "closed" | string;
  priority: "low" | "normal" | "high" | "urgent" | string;
  last_message_at?: string;
  message_count?: number;
  unread_by_client?: number;
  created_at?: string;
};

const STATUS_LABEL: Record<string, string> = {
  open: "Ouvert",
  waiting_client: "En attente client",
  waiting_staff: "En attente support",
  closed: "Fermé",
};

// Fonction pour déterminer la classe CSS du statut
function getStatusClass(status: string) {
  switch (status?.toLowerCase()) {
    case "open":
      return "bg-blue-100 text-blue-800 border-blue-200";
    case "waiting_client":
      return "bg-orange-100 text-orange-800 border-orange-200";
    case "waiting_staff":
      return "bg-amber-100 text-amber-800 border-amber-200";
    case "closed":
      return "bg-emerald-100 text-emerald-800 border-emerald-200";
    default:
      return "bg-slate-100 text-slate-600 border-slate-200";
  }
}

// Fonction pour déterminer la classe CSS de la priorité
function getPriorityClass(priority: string) {
  switch (priority?.toLowerCase()) {
    case "urgent":
      return "bg-red-100 text-red-800 border-red-200";
    case "high":
      return "bg-orange-100 text-orange-800 border-orange-200";
    case "normal":
      return "bg-blue-100 text-blue-800 border-blue-200";
    case "low":
      return "bg-slate-100 text-slate-600 border-slate-200";
    default:
      return "bg-slate-100 text-slate-600 border-slate-200";
  }
}

export default function SupportPage() {
  usePageTitle("Support");
  
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [items, setItems] = useState<Ticket[]>([]);
  const [subject, setSubject] = useState("");
  const [message, setMessage] = useState("");
  const [priority, setPriority] = useState<"low"|"normal"|"high"|"urgent">("normal");
  const [posting, setPosting] = useState(false);
  const [page, setPage] = useState(1);
  const pageSize = 5;

  // État pour la conversation
  const [selectedTicket, setSelectedTicket] = useState<Ticket | null>(null);
  const [viewMode, setViewMode] = useState<"list" | "conversation">("list");

  // Filtres & tri
  const [q, setQ] = useState("");
  const [filterStatus, setFilterStatus] = useState<string>("all");
  const [filterPriority, setFilterPriority] = useState<string>("all");
  const [unreadOnly, setUnreadOnly] = useState(false);
  const [sortBy, setSortBy] = useState<
    | "last_message_at_desc"
    | "created_at_desc"
    | "priority_desc"
    | "priority_asc"
    | "subject_asc"
  >("last_message_at_desc");

  // Catégories & formulaire dynamique
  const [category, setCategory] = useState<string>("general");
  const [contractInput, setContractInput] = useState("");
  const [salarieInput, setSalarieInput] = useState("");

  // Pièces jointes
  const [files, setFiles] = useState<File[]>([]);

  async function load() {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/tickets", { credentials: "include", cache: "no-store" });
      if (!res.ok) throw new Error(await res.text());
      const j = await res.json();
      setItems(j.items || []);
    } catch (e: any) {
      setError(e?.message || "Erreur de chargement");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => { load(); }, []);

  // S'assure que la page courante est valide quand la liste change
  useEffect(() => {
    const totalPages = Math.max(1, Math.ceil((items?.length || 0) / pageSize));
    if (page > totalPages) setPage(totalPages);
  }, [items, page, pageSize]);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!subject.trim() || !message.trim()) return;
    setPosting(true);
    setError(null);
    try {
      let res: Response;
      if (files.length > 0) {
        // Envoi multipart si pièces jointes présentes
        const fd = new FormData();
        fd.append("subject", subject.trim());
        fd.append("message", message.trim());
        fd.append("priority", priority);
        fd.append("category", category);
        if (contractInput.trim()) {
          fd.append("contract_input", contractInput.trim());
        }
        if (salarieInput.trim()) {
          fd.append("salarie_input", salarieInput.trim());
        }
        for (const f of files) fd.append("attachments", f, f.name);
        res = await fetch("/api/tickets", { method: "POST", credentials: "include", body: fd });
      } else {
        // JSON par défaut
        const payload: any = { subject: subject.trim(), message: message.trim(), priority, category };
        if (contractInput.trim()) {
          payload.contract_input = contractInput.trim();
        }
        if (salarieInput.trim()) {
          payload.salarie_input = salarieInput.trim();
        }
        res = await fetch("/api/tickets", {
          method: "POST",
          credentials: "include",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        });
      }
      if (!res.ok) throw new Error(await res.text());
      setSubject("");
      setMessage("");
      setCategory("general");
      setContractInput("");
      setSalarieInput("");
      setFiles([]);
      await load();
    } catch (e: any) {
      setError(e?.message || "Erreur lors de la création du ticket");
    } finally {
      setPosting(false);
    }
  }

  // Fonctions pour gérer la conversation
  function openTicket(ticket: Ticket) {
    setSelectedTicket(ticket);
    setViewMode("conversation");
  }

  function closeConversation() {
    setSelectedTicket(null);
    setViewMode("list");
    load(); // Recharger la liste des tickets
  }

  const hasTickets = useMemo(() => items && items.length > 0, [items]);

  // Filtrage
  const filtered = useMemo(() => {
    let list = [...(items || [])];
    if (q.trim()) {
      const qq = q.trim().toLowerCase();
      list = list.filter((t) => (t.subject || "").toLowerCase().includes(qq));
    }
    if (filterStatus !== "all") list = list.filter((t) => (t.status || "").toLowerCase() === filterStatus);
    if (filterPriority !== "all") list = list.filter((t) => (t.priority || "").toLowerCase() === filterPriority);
    if (unreadOnly) list = list.filter((t) => (t.unread_by_client || 0) > 0);
    return list;
  }, [items, q, filterStatus, filterPriority, unreadOnly]);

  // Tri
  const filteredSorted = useMemo(() => {
    const list = [...filtered];
    const toTs = (s?: string) => (s ? new Date(s).getTime() : 0);
    const prioRank: Record<string, number> = { urgent: 4, high: 3, normal: 2, low: 1 };
    switch (sortBy) {
      case "created_at_desc":
        list.sort((a, b) => toTs(b.created_at) - toTs(a.created_at));
        break;
      case "priority_desc":
        list.sort((a, b) => (prioRank[(b.priority || "").toLowerCase()] || 0) - (prioRank[(a.priority || "").toLowerCase()] || 0));
        break;
      case "priority_asc":
        list.sort((a, b) => (prioRank[(a.priority || "").toLowerCase()] || 0) - (prioRank[(b.priority || "").toLowerCase()] || 0));
        break;
      case "subject_asc":
        list.sort((a, b) => (a.subject || "").localeCompare(b.subject || "", "fr"));
        break;
      case "last_message_at_desc":
      default:
        list.sort((a, b) => toTs(b.last_message_at) - toTs(a.last_message_at));
        break;
    }
    return list;
  }, [filtered, sortBy]);

  // Pagination sur la liste filtrée/triée
  const totalPages = useMemo(() => Math.max(1, Math.ceil((filteredSorted?.length || 0) / pageSize)), [filteredSorted, pageSize]);
  const displayed = useMemo(() => {
    const start = (page - 1) * pageSize;
    return (filteredSorted || []).slice(start, start + pageSize);
  }, [filteredSorted, page, pageSize]);

  // Reset page quand filtres changent
  useEffect(() => { setPage(1); }, [q, filterStatus, filterPriority, unreadOnly, sortBy]);

  function onFilesSelected(list: FileList | null) {
    if (!list) return;
    const acc: File[] = [];
    for (const f of Array.from(list)) {
      if (f.size > 20 * 1024 * 1024) { setError(`Le fichier "${f.name}" dépasse 20 Mo`); return; }
      acc.push(f);
    }
    setFiles(acc);
  }

  return (
    <main className="p-6 max-w-7xl mx-auto">
      <div className="mb-6">
        <h1 className="text-2xl font-bold">Support</h1>
        <p className="text-slate-600 mt-1">Centre d'assistance Odentas</p>
      </div>
      
      {/* Mode conversation */}
      {viewMode === "conversation" && selectedTicket ? (
        <div className="bg-white rounded-2xl border p-6">
          <TicketConversation 
            ticket={selectedTicket} 
            onClose={closeConversation} 
          />
        </div>
      ) : (
        /* Mode liste des tickets */
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          {/* Colonne de gauche: formulaire de création - 2 colonnes */}
          <div className="lg:col-span-2">
            <div className="rounded-2xl border bg-white p-4 sticky top-6">
              <h2 className="text-lg font-semibold mb-4">Ouvrir un ticket</h2>
              {error && (
                <div className="mb-4 p-3 rounded-lg bg-red-50 border border-red-200 text-sm text-red-700">
                  {error}
                </div>
              )}
          <form onSubmit={onSubmit} className="space-y-3">
            {/* Catégorie */}
            <div>
              <label className="block text-sm font-medium mb-1">Catégorie</label>
              <select value={category} onChange={(e) => { setCategory(e.target.value); }} className="w-full px-3 py-2 rounded-lg border bg-transparent text-sm">
                <option value="general">Général</option>
                <option value="contrat">Contrat</option>
                <option value="salarie">Salarié·e</option>
                <option value="facturation">Facturation</option>
                <option value="bug">Bug / Incident</option>
                <option value="question">Question</option>
              </select>
            </div>

            {category === 'contrat' && (
              <div>
                <label className="block text-sm font-medium mb-1">Contrat lié</label>
                <input 
                  value={contractInput} 
                  onChange={(e) => setContractInput(e.target.value)} 
                  className="w-full px-3 py-2 rounded-lg border bg-transparent text-sm" 
                  placeholder="Nom du contrat ou référence..." 
                />
              </div>
            )}

            {category === 'salarie' && (
              <div>
                <label className="block text-sm font-medium mb-1">Salarié·e lié·e</label>
                <input 
                  value={salarieInput} 
                  onChange={(e) => setSalarieInput(e.target.value)} 
                  className="w-full px-3 py-2 rounded-lg border bg-transparent text-sm" 
                  placeholder="Nom du/de la salarié·e ou matricule..." 
                />
              </div>
            )}
            <div>
              <label className="block text-sm font-medium mb-1">Sujet</label>
              <input value={subject} onChange={(e) => setSubject(e.target.value)} className="w-full px-3 py-2 rounded-lg border bg-transparent text-sm" placeholder="Ex: Question sur la paie d’août" />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Message</label>
              <textarea value={message} onChange={(e) => setMessage(e.target.value)} className="w-full px-3 py-2 rounded-lg border bg-transparent text-sm min-h-[100px]" placeholder="Décrivez votre demande…" />
            </div>
            {/* Pièces jointes */}
            <div>
              <label className="block text-sm font-medium mb-1">Pièces jointes (20 Mo max/fichier)</label>
              <div className="flex items-center gap-3">
                <label className="inline-flex items-center gap-2 px-3 py-2 rounded-lg border cursor-pointer">
                  <span className="text-sm">Choisir des fichiers</span>
                  <input type="file" multiple className="hidden" onChange={(e) => onFilesSelected(e.target.files)} />
                </label>
                {files.length > 0 && (
                  <div className="text-xs text-slate-600">
                    {files.length} fichier{files.length > 1 ? "s" : ""} sélectionné{files.length > 1 ? "s" : ""}
                  </div>
                )}
              </div>
              {files.length > 0 && (
                <ul className="mt-2 text-xs text-slate-600 list-disc pl-5 space-y-1">
                  {files.map((f, i) => (
                    <li key={i} className="flex items-center gap-2">
                      <span className="truncate">{f.name}</span>
                      <button type="button" className="underline" onClick={() => setFiles((prev) => prev.filter((_, idx) => idx !== i))}>Retirer</button>
                    </li>
                  ))}
                </ul>
              )}
            </div>
            <div className="flex items-center gap-3">
              <label className="text-sm">Priorité</label>
              <select value={priority} onChange={(e) => setPriority(e.target.value as any)} className="px-2 py-1 rounded-md border text-sm bg-transparent">
                <option value="low">Basse</option>
                <option value="normal">Normale</option>
                <option value="high">Haute</option>
                <option value="urgent">Urgente</option>
              </select>
              <button disabled={posting} className="ml-auto inline-flex items-center px-3 py-2 rounded-lg bg-emerald-600 text-white text-sm hover:bg-emerald-700 disabled:opacity-50">
                Créer le ticket
              </button>
            </div>
          </form>
        </div>
      </div>

      {/* Colonne droite: liste des tickets + pagination - 2 colonnes */}
        <div className="lg:col-span-2 rounded-2xl border bg-white overflow-hidden">
          <div className="px-4 py-3 border-b">
            <div className="flex items-center gap-3">
              <h2 className="text-lg font-semibold">Vos tickets</h2>
              {hasTickets ? (
                <div className="ml-auto text-xs text-slate-500">{filteredSorted.length} / {items.length} affiché{filteredSorted.length > 1 ? 's' : ''}</div>
              ) : null}
            </div>
            {/* Barre de filtres/tri - Réorganisée sur deux lignes */}
            <div className="mt-3 space-y-3">
              {/* Première ligne : Recherche + Filtres principaux */}
              <div className="grid grid-cols-1 lg:grid-cols-4 gap-3 text-sm">
                <div className="lg:col-span-2">
                  <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Rechercher un sujet…" className="w-full px-3 py-2 rounded-lg border bg-transparent" />
                </div>
                <div>
                  <select value={filterStatus} onChange={(e) => setFilterStatus(e.target.value)} className="w-full px-2 py-2 rounded-lg border bg-transparent">
                    <option value="all">Tous statuts</option>
                    <option value="open">Ouvert</option>
                    <option value="waiting_client">En attente client</option>
                    <option value="waiting_staff">En attente support</option>
                    <option value="closed">Fermé</option>
                  </select>
                </div>
                <div>
                  <select value={filterPriority} onChange={(e) => setFilterPriority(e.target.value)} className="w-full px-2 py-2 rounded-lg border bg-transparent">
                    <option value="all">Toutes priorités</option>
                    <option value="urgent">Urgente</option>
                    <option value="high">Haute</option>
                    <option value="normal">Normale</option>
                    <option value="low">Basse</option>
                  </select>
                </div>
              </div>
              
              {/* Deuxième ligne : Options avancées + Tri */}
              <div className="grid grid-cols-1 lg:grid-cols-4 gap-3 text-sm">
                <label className="inline-flex items-center gap-2 px-3 py-2 rounded-lg border bg-transparent cursor-pointer">
                  <input type="checkbox" checked={unreadOnly} onChange={(e) => setUnreadOnly(e.target.checked)} />
                  <span>Non lus uniquement</span>
                </label>
                <div className="lg:col-span-2">
                  <select value={sortBy} onChange={(e) => setSortBy(e.target.value as any)} className="w-full px-2 py-2 rounded-lg border bg-transparent">
                    <option value="last_message_at_desc">Tri: Dernier message (récent → ancien)</option>
                    <option value="created_at_desc">Tri: Création (récent → ancien)</option>
                    <option value="priority_desc">Tri: Priorité (haut → bas)</option>
                    <option value="priority_asc">Tri: Priorité (bas → haut)</option>
                    <option value="subject_asc">Tri: Sujet (A → Z)</option>
                  </select>
                </div>
                <div className="flex items-center justify-end">
                  <button type="button" className="text-xs underline hover:no-underline" onClick={() => { setQ(""); setFilterStatus("all"); setFilterPriority("all"); setUnreadOnly(false); setSortBy("last_message_at_desc"); }}>Réinitialiser filtres</button>
                </div>
              </div>
            </div>
          </div>
          {loading ? (
            <div className="p-6 text-sm text-slate-500">Chargement…</div>
          ) : hasTickets ? (
            <div className="p-4">
              {/* Affichage des tickets en cards - Disposition en 1 colonne pour plus de lisibilité */}
              <div className="space-y-4">
                {displayed.map((t) => (
                  <div key={t.id} className="rounded-2xl border bg-white p-4 hover:shadow-md transition-shadow cursor-pointer" onClick={() => openTicket(t)}>
                    <div className="flex flex-col gap-3">
                      {/* En-tête avec sujet et badges statut/priorité */}
                      <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-2">
                        <div className="flex-1 min-w-0">
                          <h3 className="font-medium text-base truncate">{t.subject}</h3>
                          {t.unread_by_client ? (
                            <div className="inline-flex items-center gap-1 text-xs text-emerald-700 mt-1">
                              <span className="inline-block h-2 w-2 rounded-full bg-emerald-600" /> 
                              {t.unread_by_client} non lu(s)
                            </div>
                          ) : null}
                        </div>
                        <div className="flex items-center gap-2 flex-shrink-0">
                          <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium border ${getStatusClass(t.status)}`}>
                            {STATUS_LABEL[t.status] || t.status}
                          </span>
                          <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium border ${getPriorityClass(t.priority)}`}>
                            {String(t.priority || '').toUpperCase() || 'NORMAL'}
                          </span>
                        </div>
                      </div>
                      
                      {/* Métadonnées du ticket */}
                      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 text-sm text-slate-600">
                        <div className="flex items-center gap-4">
                          {typeof t.message_count === 'number' && (
                            <span className="flex items-center gap-1">
                              <MessageCircle className="w-4 h-4" />
                              {t.message_count} message{t.message_count > 1 ? 's' : ''}
                            </span>
                          )}
                          {t.created_at && (
                            <span className="text-xs">
                              Créé le {new Date(t.created_at).toLocaleDateString("fr-FR")}
                            </span>
                          )}
                        </div>
                        <div className="text-xs">
                          {t.last_message_at ? (
                            <span>
                              Dernier message: {new Date(t.last_message_at).toLocaleString("fr-FR", {
                                day: "2-digit",
                                month: "2-digit", 
                                year: "numeric",
                                hour: "2-digit",
                                minute: "2-digit"
                              })}
                            </span>
                          ) : (
                            <span>Aucun message</span>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              {/* Pagination */}
              {totalPages > 1 ? (
                <div className="flex items-center justify-between px-4 py-4 border-t text-sm mt-6">
                  <button
                    onClick={() => setPage((p) => Math.max(1, p - 1))}
                    disabled={page === 1}
                    className="px-3 py-2 rounded-lg border disabled:opacity-50 hover:bg-slate-50"
                  >
                    Précédent
                  </button>
                  <div className="flex items-center gap-2">
                    {Array.from({ length: totalPages }).map((_, i) => {
                      const n = i + 1;
                      const active = n === page;
                      return (
                        <button
                          key={n}
                          onClick={() => setPage(n)}
                          className={`h-8 w-8 rounded-lg border text-sm font-medium transition-colors ${
                            active 
                              ? 'bg-slate-900 text-white' 
                              : 'hover:bg-slate-50'
                          }`}
                        >
                          {n}
                        </button>
                      );
                    })}
                  </div>
                  <button
                    onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                    disabled={page === totalPages}
                    className="px-3 py-2 rounded-lg border disabled:opacity-50 hover:bg-slate-50"
                  >
                    Suivant
                  </button>
                </div>
              ) : null}
            </div>
          ) : (
            <div className="p-6 text-sm text-slate-500">Aucun ticket pour le moment.</div>
          )}
        </div>
        </div>
      )}
    </main>
  );
}
