"use client";

import { useMemo, useState } from "react";
import ConfirmableForm from "@/components/ConfirmableForm";

type ClientMember = {
  user_id: string;
  email: string;
  first_name: string | null;
  organization_name: string;
  role: string | null;
  created_at: string;
  revoked: boolean;
  revoked_at: string | null;
  org_id: string;
};

type Organization = {
  id: string;
  name: string;
  structure_api: string | null;
};

type SortField = "first_name" | "email" | "organization_name" | "role" | "created_at";

export default function ClientUsersTable({ 
  members, 
  organizations 
}: { 
  members: ClientMember[]; 
  organizations: Organization[];
}) {
  // Filtres
  const [searchQuery, setSearchQuery] = useState("");
  const [orgFilter, setOrgFilter] = useState<string | null>(null);
  const [roleFilter, setRoleFilter] = useState<string | null>(null);
  const [statusFilter, setStatusFilter] = useState<string | null>(null);

  // Tri
  const [sortField, setSortField] = useState<SortField>("created_at");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");

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

  // Listes pour les filtres
  const uniqueOrgs = useMemo(() => {
    return Array.from(new Set(members.map(m => m.organization_name)))
      .filter(Boolean)
      .sort();
  }, [members]);

  const uniqueRoles = useMemo(() => {
    return Array.from(new Set(members.map(m => m.role)))
      .filter((r): r is string => Boolean(r))
      .sort();
  }, [members]);

  // Filtrage et tri
  const filteredAndSortedMembers = useMemo(() => {
    let filtered = members;

    // Recherche
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(m => 
        m.first_name?.toLowerCase().includes(query) ||
        m.email?.toLowerCase().includes(query) ||
        m.organization_name?.toLowerCase().includes(query)
      );
    }

    // Filtre organisation
    if (orgFilter) {
      filtered = filtered.filter(m => m.organization_name === orgFilter);
    }

    // Filtre rôle
    if (roleFilter) {
      filtered = filtered.filter(m => m.role === roleFilter);
    }

    // Filtre statut
    if (statusFilter === "active") {
      filtered = filtered.filter(m => !m.revoked);
    } else if (statusFilter === "revoked") {
      filtered = filtered.filter(m => m.revoked);
    }

    // Tri
    const sorted = [...filtered].sort((a, b) => {
      let aValue: any = a[sortField];
      let bValue: any = b[sortField];

      // Gérer les valeurs nulles
      if (aValue === null || aValue === undefined) return 1;
      if (bValue === null || bValue === undefined) return -1;

      // Tri par date
      if (sortField === "created_at") {
        aValue = new Date(aValue).getTime();
        bValue = new Date(bValue).getTime();
      } else {
        // Tri alphabétique
        aValue = String(aValue).toLowerCase();
        bValue = String(bValue).toLowerCase();
      }

      if (aValue < bValue) return sortOrder === "asc" ? -1 : 1;
      if (aValue > bValue) return sortOrder === "asc" ? 1 : -1;
      return 0;
    });

    return sorted;
  }, [members, searchQuery, orgFilter, roleFilter, statusFilter, sortField, sortOrder]);

  const hasActiveFilters = searchQuery || orgFilter || roleFilter || statusFilter;

  const clearFilters = () => {
    setSearchQuery("");
    setOrgFilter(null);
    setRoleFilter(null);
    setStatusFilter(null);
  };

  // Composant pour l'en-tête triable
  const SortableHeader = ({ field, label }: { field: SortField; label: string }) => (
    <th 
      className="text-left px-4 py-3 font-medium cursor-pointer hover:bg-slate-100 select-none transition-colors"
      onClick={() => handleSort(field)}
    >
      <div className="flex items-center gap-2">
        {label}
        {sortField === field && (
          <span className="text-xs">{sortOrder === "asc" ? "↑" : "↓"}</span>
        )}
      </div>
    </th>
  );

  return (
    <section className="space-y-3">
      <h2 className="text-base font-semibold">
        Utilisateurs Clients ({filteredAndSortedMembers.length}{members.length !== filteredAndSortedMembers.length && ` / ${members.length}`})
      </h2>

      {/* Filtres */}
      <div className="bg-slate-50 rounded-xl p-4">
        <div className="grid grid-cols-1 sm:grid-cols-4 gap-3">
          {/* Recherche */}
          <div>
            <label className="block text-xs font-medium text-slate-700 mb-1">Recherche</label>
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Nom, email, organisation..."
              className="w-full px-3 py-2 border rounded-lg text-sm bg-white"
            />
          </div>

          {/* Filtre Organisation */}
          <div>
            <label className="block text-xs font-medium text-slate-700 mb-1">Organisation</label>
            <select
              value={orgFilter || ""}
              onChange={(e) => setOrgFilter(e.target.value || null)}
              className="w-full px-3 py-2 border rounded-lg text-sm bg-white"
            >
              <option value="">Toutes</option>
              {uniqueOrgs.map(org => (
                <option key={org} value={org}>{org}</option>
              ))}
            </select>
          </div>

          {/* Filtre Rôle */}
          <div>
            <label className="block text-xs font-medium text-slate-700 mb-1">Niveau</label>
            <select
              value={roleFilter || ""}
              onChange={(e) => setRoleFilter(e.target.value || null)}
              className="w-full px-3 py-2 border rounded-lg text-sm bg-white"
            >
              <option value="">Tous</option>
              {uniqueRoles.map(role => (
                <option key={role} value={role}>{role}</option>
              ))}
            </select>
          </div>

          {/* Filtre Statut */}
          <div>
            <label className="block text-xs font-medium text-slate-700 mb-1">Statut</label>
            <select
              value={statusFilter || ""}
              onChange={(e) => setStatusFilter(e.target.value || null)}
              className="w-full px-3 py-2 border rounded-lg text-sm bg-white"
            >
              <option value="">Tous</option>
              <option value="active">Actifs</option>
              <option value="revoked">Révoqués</option>
            </select>
          </div>
        </div>

        {/* Bouton réinitialiser */}
        {hasActiveFilters && (
          <div className="mt-3">
            <button
              onClick={clearFilters}
              className="px-4 py-2 rounded-lg text-sm bg-slate-200 hover:bg-slate-300 transition-colors"
            >
              Réinitialiser les filtres
            </button>
          </div>
        )}
      </div>

      {/* Tableau */}
      <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="first_name" label="Prénom" />
              <SortableHeader field="email" label="Email" />
              <SortableHeader field="organization_name" label="Organisation" />
              <SortableHeader field="role" label="Niveau" />
              <SortableHeader field="created_at" label="Créé le" />
              <th className="text-left px-4 py-3">Statut</th>
              <th className="text-left px-4 py-3">Actions</th>
            </tr>
          </thead>
          <tbody>
            {filteredAndSortedMembers.length === 0 ? (
              <tr>
                <td colSpan={7} className="px-4 py-6 text-center text-slate-500">
                  {hasActiveFilters ? "Aucun utilisateur ne correspond aux filtres." : "Aucun utilisateur trouvé."}
                </td>
              </tr>
            ) : (
              filteredAndSortedMembers.map((m) => {
                const created = m.created_at ? new Date(m.created_at) : null;
                const createdFmt = created
                  ? created.toLocaleString("fr-FR", {
                      year: "numeric",
                      month: "2-digit",
                      day: "2-digit",
                      hour: "2-digit",
                      minute: "2-digit",
                    })
                  : "—";
                const status = m.revoked ? "Révoqué" : "Actif";
                const disabled = !!m.revoked;
                
                return (
                  <tr key={`${m.user_id}-${m.org_id}`} className="border-t align-top hover:bg-slate-50 transition-colors">
                    <td className="px-4 py-3 whitespace-nowrap">{m.first_name || "—"}</td>
                    <td className="px-4 py-3">{m.email}</td>
                    <td className="px-4 py-3">{m.organization_name}</td>
                    <td className="px-4 py-3 uppercase tracking-wide text-xs">{m.role || "—"}</td>
                    <td className="px-4 py-3 whitespace-nowrap">{createdFmt}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex items-center px-2 py-1 rounded text-xs font-medium ${
                        !disabled ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                      }`}>
                        {status}
                      </span>
                    </td>
                    <td className="px-4 py-2">
                      <div className="flex flex-col gap-2">
                        <ConfirmableForm
                          method="post"
                          action="/api/staff/users/update-role"
                          className="flex items-center gap-2"
                          disabled={disabled}
                          confirmTitle="Confirmer la modification du niveau"
                          confirmMessage={`Voulez-vous vraiment appliquer ce niveau à ${m.first_name || m.email} ?`}
                        >
                          <input type="hidden" name="org_id" value={m.org_id} />
                          <input type="hidden" name="user_id" value={m.user_id} />
                          <select
                            name="role"
                            defaultValue={m.role || "ADMIN"}
                            disabled={disabled}
                            className="px-2 py-1 rounded border text-xs"
                          >
                            <option value="SUPER_ADMIN">Super Admin</option>
                            <option value="ADMIN">Admin</option>
                            <option value="AGENT">Agent</option>
                            <option value="COMPTA">Compta</option>
                          </select>
                          <button
                            type="submit"
                            disabled={disabled}
                            className="px-3 py-1 rounded bg-slate-900 text-white text-xs hover:bg-slate-700 disabled:opacity-50"
                          >
                            Modifier
                          </button>
                        </ConfirmableForm>

                        {!disabled ? (
                          <ConfirmableForm
                            method="post"
                            action="/api/staff/users/revoke"
                            className="flex items-center gap-2"
                            disabled={disabled}
                            confirmTitle="Confirmer la révocation"
                            confirmMessage={`Voulez-vous révoquer l'accès de ${m.first_name || m.email} pour cette structure ?`}
                            confirmCta="Révoquer"
                          >
                            <input type="hidden" name="org_id" value={m.org_id} />
                            <input type="hidden" name="user_id" value={m.user_id} />
                            <button
                              type="submit"
                              disabled={disabled}
                              className="px-3 py-1 rounded text-xs bg-red-600 text-white hover:bg-red-700 disabled:opacity-50"
                            >
                              Supprimer
                            </button>
                          </ConfirmableForm>
                        ) : (
                          <ConfirmableForm
                            method="post"
                            action="/api/staff/users/unrevoke"
                            className="flex items-center gap-2"
                            disabled={false}
                            confirmTitle="Confirmer la réintégration"
                            confirmMessage={`Réintégrer ${m.first_name || m.email} et lui redonner l'accès à cette structure ?`}
                            confirmCta="Réintégrer"
                          >
                            <input type="hidden" name="org_id" value={m.org_id} />
                            <input type="hidden" name="user_id" value={m.user_id} />
                            <button
                              type="submit"
                              className="px-3 py-1 rounded text-xs bg-emerald-600 text-white hover:bg-emerald-700"
                            >
                              Réintégrer
                            </button>
                          </ConfirmableForm>
                        )}
                        {disabled && (
                          <div className="text-xs text-slate-500">Utilisateur révoqué — accès désactivé</div>
                        )}
                      </div>
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>
    </section>
  );
}
