import { Card } from '@/components/ui/card';
import { formatDateTimeFr, formatRelative } from '@/lib/relative-time';
import type { ActivityTeamRow } from '@/types/activity';
import { formatCount, type Translate } from './activity-format';
import { ActorAvatar, TeamStateChip, TeamStateLegend } from './ActivityShared';

const NS = 'activity';

interface Props {
    team: ActivityTeamRow[];
    /** Colonne franchise : siège uniquement (`options.franchises` non nul). */
    showFranchise: boolean;
    /** Les connexions sont-elles suivies ? Sinon « Jamais » mentirait : on écrit « — ». */
    loginsTracked: boolean;
    now: Date;
    locale: string;
    t: Translate;
    onOpenMember: (row: ActivityTeamRow) => void;
}

const TH = 'px-3 py-2 text-left font-medium sm:px-4';
const TD = 'px-3 py-2.5 align-middle sm:px-4';

/**
 * Qui est là, qui ne l'est plus. L'état se lit sur la dernière ACTION, pas sur
 * la dernière connexion : quelqu'un qui se connecte chaque jour sans rien
 * enregistrer n'est pas « actif » dans le Manager.
 */
export function ActivityTeamTable({ team, showFranchise, loginsTracked, now, locale, t, onOpenMember }: Props) {
    const never = t(NS, 'team_never', 'Jamais');

    const timeCell = (iso: string | null, tracked: boolean) => {
        if (!tracked) {
            return (
                <span className="text-muted-foreground" title={t(NS, 'team_not_tracked', 'Pas encore suivi')}>
                    —
                </span>
            );
        }
        if (!iso) {
            return (
                <span className="text-muted-foreground" title={t(NS, 'team_never_hint', 'Aucune trace depuis le début du suivi')}>
                    {never}
                </span>
            );
        }

        return (
            <time dateTime={iso} title={formatDateTimeFr(iso)} className="whitespace-nowrap">
                {formatRelative(iso, locale, now)}
            </time>
        );
    };

    return (
        <div className="flex flex-col gap-2">
            <div data-tour="activity-team" className="text-muted-foreground flex flex-col gap-2 text-xs lg:flex-row lg:items-center lg:justify-between">
                <p>{t(NS, 'team_hint', 'Cliquez sur un membre pour voir ses actions dans le flux.')}</p>
                <TeamStateLegend t={t} />
            </div>

            <Card className="gap-0 overflow-hidden py-0">
                {team.length === 0 ? (
                    <p className="text-muted-foreground px-6 py-12 text-center text-sm">{t(NS, 'team_empty', 'Aucun membre dans ce périmètre.')}</p>
                ) : (
                    // Le défilement horizontal reste DANS la carte : la page, elle, ne déborde jamais.
                    <div className="overflow-x-auto">
                        <table className="w-full text-sm">
                            <thead className="bg-muted/50 text-muted-foreground border-b text-xs">
                                <tr>
                                    <th scope="col" className={TH}>
                                        {t(NS, 'team_member', 'Membre')}
                                    </th>
                                    {showFranchise && (
                                        <th scope="col" className={`${TH} hidden md:table-cell`}>
                                            {t(NS, 'team_franchise', 'Franchise')}
                                        </th>
                                    )}
                                    <th scope="col" className={`${TH} hidden sm:table-cell`}>
                                        {t(NS, 'team_last_login', 'Dernière connexion')}
                                    </th>
                                    <th scope="col" className={TH}>
                                        {t(NS, 'team_last_action', 'Dernière action')}
                                    </th>
                                    {/* Masquée sous 640 px : au téléphone, l'ÉTAT doit rester visible
                                        sans défilement horizontal — c'est le signal que l'on vient lire. */}
                                    <th scope="col" className={`${TH} hidden text-right sm:table-cell`}>
                                        {t(NS, 'team_actions', 'Actions sur la période')}
                                    </th>
                                    <th scope="col" className={TH}>
                                        {t(NS, 'team_state', 'État')}
                                    </th>
                                </tr>
                            </thead>
                            <tbody className="divide-y">
                                {team.map((row) => (
                                    <tr key={row.id} className="hover:bg-muted/40 cursor-pointer transition-colors" onClick={() => onOpenMember(row)}>
                                        <td className={TD}>
                                            <button
                                                type="button"
                                                onClick={(event) => {
                                                    // La ligne entière est cliquable ; le bouton porte le focus clavier.
                                                    event.stopPropagation();
                                                    onOpenMember(row);
                                                }}
                                                title={t(NS, 'team_open_feed', 'Voir ses actions dans le flux')}
                                                className="focus-visible:ring-ring flex min-w-0 items-center gap-2.5 rounded-md text-left focus-visible:ring-2 focus-visible:outline-none"
                                            >
                                                <ActorAvatar actor={{ initials: row.initials, name: row.name, is_system: false }} size="sm" />
                                                <span className="min-w-0">
                                                    <span className="block max-w-[180px] truncate font-medium">{row.name}</span>
                                                    {row.role && <span className="text-muted-foreground block max-w-[180px] truncate text-xs">{row.role}</span>}
                                                </span>
                                            </button>
                                        </td>
                                        {showFranchise && <td className={`${TD} hidden md:table-cell`}>{row.franchise ?? t(NS, 'team_hq', 'Siège')}</td>}
                                        <td className={`${TD} hidden sm:table-cell`}>{timeCell(row.last_login_at, loginsTracked)}</td>
                                        <td className={TD}>{timeCell(row.last_action_at, true)}</td>
                                        <td className={`${TD} hidden text-right tabular-nums sm:table-cell`}>{formatCount(row.actions_in_range, locale)}</td>
                                        <td className={TD}>
                                            <TeamStateChip state={row.state} t={t} />
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </Card>
        </div>
    );
}
