'use client';

import {
  ArrowDown,
  ArrowUp,
  ChevronsUpDown,
  Users as UsersIcon,
} from 'lucide-react';

import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import type { AuthUser, Utilisateur } from '@/lib/api';
import {
  FONCTIONS_UTI_S,
  fonctionsOuvertes,
  formatDateUtilisateur,
  initiales,
  libelleRole,
  nomComplet,
} from '@/lib/utilisateurs';
import { cn } from '@/lib/utils';

import { UtilisateurActions } from './utilisateur-actions';

export type ColonneTri = 'nom' | 'email' | 'statut' | 'created_at';
export type SensTri = 'asc' | 'desc';

type UtilisateursListProps = {
  utilisateurs: Utilisateur[];
  currentUser: AuthUser | null;
  onUtilisateurUpdated: (utilisateur: Utilisateur) => void;
  tri: ColonneTri;
  sensTri: SensTri;
  onTrier: (colonne: ColonneTri) => void;
  /** Vrai lorsque l'absence de lignes résulte d'un filtre et non d'un vide réel. */
  filtreActif: boolean;
};

type EnteteTriableProps = {
  label: string;
  actif: boolean;
  sens: SensTri;
  onClick: () => void;
};

function EnteteTriable({ label, actif, sens, onClick }: EnteteTriableProps) {
  const Icone = !actif ? ChevronsUpDown : sens === 'asc' ? ArrowUp : ArrowDown;

  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(
        'group -ml-2 inline-flex items-center gap-1.5 rounded px-2 py-1 uppercase tracking-wide transition-colors hover:text-foreground',
        actif && 'text-foreground',
      )}
    >
      {label}
      <Icone
        className={cn(
          'h-3.5 w-3.5 transition-opacity',
          actif ? 'opacity-100' : 'opacity-40 group-hover:opacity-100',
        )}
      />
    </button>
  );
}

function PastilleStatut({ actif }: { actif: boolean }) {
  return (
    <span
      className={cn(
        'inline-flex items-center gap-1.5 whitespace-nowrap rounded-full px-2 py-0.5 text-xs font-medium',
        actif
          ? 'bg-emerald-100 text-emerald-700'
          : 'bg-destructive/10 text-destructive',
      )}
    >
      <span
        className={cn(
          'h-1.5 w-1.5 rounded-full',
          actif ? 'bg-emerald-600' : 'bg-destructive',
        )}
      />
      {actif ? 'Actif' : 'Désactivé'}
    </span>
  );
}

/**
 * §5.6.3 : seul un UTI-S porte un profil de fonctions. Au-delà de trois
 * fonctions ouvertes, la liste est résumée pour ne pas déformer la ligne, le
 * détail restant accessible en infobulle.
 */
function CelluleProfil({ utilisateur }: { utilisateur: Utilisateur }) {
  if (utilisateur.role_ccfn !== 'UTI-S') {
    return <span className="text-sm text-muted-foreground">Sans objet</span>;
  }

  const ouvertes = fonctionsOuvertes(utilisateur.profil);

  if (ouvertes.length === 0) {
    return (
      <span className="text-sm text-muted-foreground">Aucune fonction</span>
    );
  }

  const visibles = ouvertes.slice(0, 3);
  const restantes = ouvertes.length - visibles.length;

  return (
    <div
      className="flex flex-wrap items-center gap-1"
      title={ouvertes.map((fonction) => fonction.label).join(', ')}
    >
      {visibles.map((fonction) => (
        <Badge
          key={fonction.key}
          variant="outline"
          className="text-xs font-normal"
        >
          {fonction.labelCourt}
        </Badge>
      ))}
      {restantes > 0 ? (
        <span className="text-xs text-muted-foreground">+{restantes}</span>
      ) : null}
      <span className="ml-1 text-xs tabular-nums text-muted-foreground">
        {ouvertes.length}/{FONCTIONS_UTI_S.length}
      </span>
    </div>
  );
}

export function UtilisateursList({
  utilisateurs,
  currentUser,
  onUtilisateurUpdated,
  tri,
  sensTri,
  onTrier,
  filtreActif,
}: UtilisateursListProps) {
  if (utilisateurs.length === 0) {
    return (
      <div className="flex flex-col items-center gap-2 px-6 py-16 text-center">
        <UsersIcon className="h-8 w-8 text-muted-foreground/60" />
        <p className="font-medium">Aucun utilisateur</p>
        <p className="max-w-sm text-sm text-muted-foreground">
          {filtreActif
            ? 'Aucun compte ne correspond aux filtres appliqués. Élargissez la recherche ou réinitialisez-la.'
            : 'Aucun compte n’est encore rattaché à votre périmètre d’administration. Créez-en un pour commencer.'}
        </p>
      </div>
    );
  }

  return (
    <Table>
      <TableHeader>
        <TableRow className="hover:bg-transparent">
          <TableHead>
            <EnteteTriable
              label="Utilisateur"
              actif={tri === 'nom'}
              sens={sensTri}
              onClick={() => onTrier('nom')}
            />
          </TableHead>
          <TableHead>
            <EnteteTriable
              label="Contact"
              actif={tri === 'email'}
              sens={sensTri}
              onClick={() => onTrier('email')}
            />
          </TableHead>
          <TableHead className="hidden md:table-cell">Rôle</TableHead>
          <TableHead className="hidden xl:table-cell">
            Fonctions
          </TableHead>
          <TableHead>
            <EnteteTriable
              label="Statut"
              actif={tri === 'statut'}
              sens={sensTri}
              onClick={() => onTrier('statut')}
            />
          </TableHead>
          <TableHead className="hidden lg:table-cell">
            <EnteteTriable
              label="Créé le"
              actif={tri === 'created_at'}
              sens={sensTri}
              onClick={() => onTrier('created_at')}
            />
          </TableHead>
          <TableHead className="text-right">Actions</TableHead>
        </TableRow>
      </TableHeader>

      <TableBody>
        {utilisateurs.map((utilisateur) => (
          <TableRow
            key={utilisateur.id}
            className={cn(!utilisateur.actif && 'bg-muted/30')}
          >
            <TableCell>
              <div className="flex items-center gap-3">
                <Avatar className="h-9 w-9">
                  <AvatarFallback className="text-xs">
                    {initiales(utilisateur)}
                  </AvatarFallback>
                </Avatar>
                <div className="min-w-0">
                  <p className="truncate font-medium">
                    {nomComplet(utilisateur)}
                  </p>
                  <p className="text-xs text-muted-foreground md:hidden">
                    {utilisateur.role_ccfn}
                  </p>
                </div>
              </div>
            </TableCell>

            <TableCell>
              <p className="truncate text-sm">{utilisateur.email}</p>
              <p className="text-xs text-muted-foreground">
                {utilisateur.telephone?.trim() || 'Téléphone non renseigné'}
              </p>
            </TableCell>

            <TableCell className="hidden md:table-cell">
              <Badge variant="secondary" className="font-normal">
                {utilisateur.role_ccfn}
              </Badge>
              <span className="mt-0.5 block text-xs text-muted-foreground">
                {libelleRole(utilisateur.role_ccfn)}
              </span>
            </TableCell>

            <TableCell className="hidden xl:table-cell">
              <CelluleProfil utilisateur={utilisateur} />
            </TableCell>

            <TableCell>
              <PastilleStatut actif={utilisateur.actif} />
            </TableCell>

            <TableCell className="hidden whitespace-nowrap text-sm text-muted-foreground lg:table-cell">
              {formatDateUtilisateur(utilisateur.created_at)}
            </TableCell>

            <TableCell className="text-right">
              <UtilisateurActions
                utilisateur={utilisateur}
                currentUser={currentUser}
                onUtilisateurUpdated={onUtilisateurUpdated}
              />
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
}
