"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import { ArrowUpDown, ArrowUp, ArrowDown, Copy, Check } from "lucide-react";

type Client = {
  id: string;
  name: string;
  code_employeur: string | null;
  siret: string | null;
  entree_en_relation: string | null;
  agrement_aem: string | null;
};

type SortField = "code_employeur" | "name" | "entree_en_relation" | "siret" | "agrement_aem";
type SortOrder = "asc" | "desc";

function formatDate(d?: string | null) {
  if (!d) return "—";
  try {
    return new Intl.DateTimeFormat("fr-FR", { dateStyle: "medium" }).format(new Date(d));
  } catch {
    return d;
  }
}

export default function StaffClientsPage() {
  const router = useRouter();
  const [searchQuery, setSearchQuery] = useState("");
  const [sortField, setSortField] = useState<SortField>("name");
  const [sortOrder, setSortOrder] = useState<SortOrder>("asc");
  const [copiedField, setCopiedField] = useState<string | null>(null);

  // Récupération des clients
  const { data: clients = [], isLoading, error } = useQuery<Client[]>({
    queryKey: ["staff-clients"],
    queryFn: async () => {
      const res = await fetch("/api/staff/clients", {
        cache: "no-store",
        credentials: "include"
      });
      if (!res.ok) {
        throw new Error("Erreur lors de la récupération des clients");
      }
      return res.json();
    },
  });

  // Fonction de copie
  const handleCopy = (text: string, fieldId: string, e: React.MouseEvent) => {
    e.stopPropagation(); // Empêcher l'ouverture du détail
    if (text && text !== "—") {
      navigator.clipboard.writeText(text);
      setCopiedField(fieldId);
      setTimeout(() => setCopiedField(null), 2000);
    }
  };

  // Fonction de tri
  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortField(field);
      setSortOrder("asc");
    }
  };

  // Tri des clients
  const sortedClients = [...clients].sort((a, b) => {
    const aValue = a[sortField] || "";
    const bValue = b[sortField] || "";
    
    if (aValue < bValue) return sortOrder === "asc" ? -1 : 1;
    if (aValue > bValue) return sortOrder === "asc" ? 1 : -1;
    return 0;
  });

  // Filtrage par recherche
  const filteredClients = sortedClients.filter(client => {
    const query = searchQuery.toLowerCase();
    return (
      client.name?.toLowerCase().includes(query) ||
      client.code_employeur?.toLowerCase().includes(query) ||
      client.siret?.toLowerCase().includes(query) ||
      client.agrement_aem?.toLowerCase().includes(query)
    );
  });

  // Composant pour l'en-tête de colonne triable
  const SortableHeader = ({ field, label }: { field: SortField; label: string }) => (
    <th 
      className="text-left px-4 py-2 font-medium cursor-pointer hover:bg-slate-100 select-none"
      onClick={() => handleSort(field)}
    >
      <div className="flex items-center gap-2">
        {label}
        {sortField === field ? (
          sortOrder === "asc" ? (
            <ArrowUp className="w-4 h-4" />
          ) : (
            <ArrowDown className="w-4 h-4" />
          )
        ) : (
          <ArrowUpDown className="w-4 h-4 opacity-30" />
        )}
      </div>
    </th>
  );

  if (isLoading) {
    return (
      <main className="p-6">
        <h1 className="text-lg font-semibold">Chargement...</h1>
      </main>
    );
  }

  if (error) {
    return (
      <main className="p-6">
        <h1 className="text-lg font-semibold">Erreur</h1>
        <p className="text-sm text-rose-600">Erreur lors de la récupération des clients</p>
      </main>
    );
  }

  return (
    <main className="p-6 space-y-4">
      <div className="flex items-center justify-between gap-4">
        <h1 className="text-lg font-semibold">Clients</h1>
        <div className="flex items-center gap-2">
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Rechercher…"
            className="hidden md:block px-3 py-2 rounded-lg border bg-transparent text-sm"
          />
          <Link href="/staff/clients/nouveau" className="inline-flex items-center gap-2 px-3 py-2 rounded-lg text-sm bg-emerald-600 text-white hover:bg-emerald-700">
            + Nouveau client
          </Link>
        </div>
      </div>

      <div className="rounded-2xl border bg-white overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-slate-50 text-slate-600">
            <tr>
              <SortableHeader field="code_employeur" label="Code employeur" />
              <SortableHeader field="name" label="Nom" />
              <SortableHeader field="entree_en_relation" label="Entrée en relation" />
              <SortableHeader field="siret" label="SIRET" />
              <SortableHeader field="agrement_aem" label="AEM" />
            </tr>
          </thead>
          <tbody>
            {filteredClients.length > 0 ? (
              filteredClients.map((client) => (
                <tr 
                  key={client.id} 
                  className="border-t hover:bg-slate-50 cursor-pointer transition-colors"
                  onClick={() => router.push(`/staff/clients/${client.id}`)}
                >
                  <td className="px-4 py-2">{client.code_employeur || "—"}</td>
                  <td className="px-4 py-2 font-medium">{client.name}</td>
                  <td className="px-4 py-2">{formatDate(client.entree_en_relation)}</td>
                  <td 
                    className="px-4 py-2 cursor-pointer hover:bg-slate-100 group relative"
                    onClick={(e) => handleCopy(client.siret || "", `siret-${client.id}`, e)}
                    title="Cliquer pour copier"
                  >
                    <div className="flex items-center gap-2">
                      <span>{client.siret || "—"}</span>
                      {client.siret && (
                        copiedField === `siret-${client.id}` ? (
                          <Check className="w-3 h-3 text-green-600" />
                        ) : (
                          <Copy className="w-3 h-3 text-slate-400 opacity-0 group-hover:opacity-100 transition-opacity" />
                        )
                      )}
                    </div>
                  </td>
                  <td 
                    className="px-4 py-2 cursor-pointer hover:bg-slate-100 group relative"
                    onClick={(e) => handleCopy(client.agrement_aem || "", `aem-${client.id}`, e)}
                    title="Cliquer pour copier"
                  >
                    <div className="flex items-center gap-2">
                      <span>{client.agrement_aem || "—"}</span>
                      {client.agrement_aem && (
                        copiedField === `aem-${client.id}` ? (
                          <Check className="w-3 h-3 text-green-600" />
                        ) : (
                          <Copy className="w-3 h-3 text-slate-400 opacity-0 group-hover:opacity-100 transition-opacity" />
                        )
                      )}
                    </div>
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td className="px-4 py-6 text-center text-slate-500" colSpan={5}>
                  {searchQuery ? "Aucun client ne correspond à votre recherche." : "Aucun client pour le moment."}
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </main>
  );
}
