import AppNav from '@/Components/AppNav';
import { Button, Card } from '@/Components/ui';
import { Head, router } from '@inertiajs/react';
import { Mail } from 'lucide-react';
import { useState } from 'react';

/**
 * In-app pending-invitations surface (Team Workspaces) — the bell/switcher twin
 * of the email accept link. Lists invites addressed to the logged-in user with
 * Accept / Decline keyed by invite id (no raw token). Backed by
 * `WorkspaceInvitationController::invitations`.
 */
type Invitation = {
    id: number;
    workspace: string | null;
    role: 'editor' | 'viewer' | string;
    inviter: string | null;
    expires_at: string | null;
};

type Props = {
    invitations: Invitation[];
};

function roleLabel(role: string): string {
    return role === 'viewer' ? 'Viewer' : role === 'editor' ? 'Editor' : role;
}

function expiryLabel(iso: string | null): string {
    if (!iso) return '';
    const ms = new Date(iso).getTime();
    if (Number.isNaN(ms)) return '';
    const days = Math.ceil((ms - Date.now()) / 86_400_000);
    if (days <= 0) return 'Expires soon';
    if (days === 1) return 'Expires in 1 day';
    return `Expires in ${days} days`;
}

export default function WorkspaceInvitations({ invitations }: Props) {
    // Per-row busy state keyed by `${id}:${action}` so two rows don't lock each
    // other and the spinner lands on the clicked button.
    const [busy, setBusy] = useState<string | null>(null);

    const act = (id: number, action: 'accept' | 'decline') => {
        setBusy(`${id}:${action}`);
        router.post(
            `/workspace/invitations/${id}/${action}`,
            {},
            { onFinish: () => setBusy(null) },
        );
    };

    return (
        <>
            <Head title="Workspace invitations" />
            <div className="flex min-h-screen flex-col bg-background text-foreground">
                <AppNav />
                <main className="mx-auto w-full max-w-2xl flex-1 px-6 py-8">
                    <div>
                        <h1 className="text-xl font-semibold tracking-tight">
                            Workspace invitations
                        </h1>
                        <p className="mt-1 text-[12px] text-muted-foreground">
                            {invitations.length > 0
                                ? `${invitations.length} pending`
                                : 'No pending invitations.'}
                        </p>
                    </div>

                    <Card padding="none" className="mt-5 overflow-hidden">
                        {invitations.length === 0 ? (
                            <div
                                className="flex flex-col items-center gap-2 px-6 py-16 text-center"
                                data-testid="invitations-empty"
                            >
                                <Mail
                                    className="h-6 w-6 text-muted-foreground/50"
                                    strokeWidth={1.5}
                                />
                                <p className="text-[12px] text-muted-foreground">
                                    You have no pending workspace invitations.
                                </p>
                            </div>
                        ) : (
                            <ul className="divide-y divide-border">
                                {invitations.map((inv) => {
                                    const name = inv.workspace ?? 'a workspace';
                                    return (
                                        <li
                                            key={inv.id}
                                            data-testid={`invitation-row-${inv.id}`}
                                            className="flex flex-wrap items-center justify-between gap-3 px-4 py-4"
                                        >
                                            <div className="min-w-0 flex-1">
                                                <p className="text-[14px] font-medium text-foreground">
                                                    {name}
                                                </p>
                                                <p className="mt-0.5 text-[12px] text-muted-foreground">
                                                    {inv.inviter
                                                        ? `${inv.inviter} invited you as ${roleLabel(inv.role)}`
                                                        : `Invited as ${roleLabel(inv.role)}`}
                                                </p>
                                                {inv.expires_at && (
                                                    <p className="mt-1 text-[11px] text-muted-foreground/70">
                                                        {expiryLabel(inv.expires_at)}
                                                    </p>
                                                )}
                                            </div>
                                            <div className="flex shrink-0 gap-2">
                                                <Button
                                                    size="md"
                                                    onClick={() => act(inv.id, 'accept')}
                                                    disabled={busy !== null}
                                                    data-testid={`invitation-accept-${inv.id}`}
                                                >
                                                    {busy === `${inv.id}:accept`
                                                        ? 'Joining…'
                                                        : 'Accept'}
                                                </Button>
                                                <Button
                                                    size="md"
                                                    variant="secondary"
                                                    onClick={() => act(inv.id, 'decline')}
                                                    disabled={busy !== null}
                                                    data-testid={`invitation-decline-${inv.id}`}
                                                >
                                                    {busy === `${inv.id}:decline`
                                                        ? 'Declining…'
                                                        : 'Decline'}
                                                </Button>
                                            </div>
                                        </li>
                                    );
                                })}
                            </ul>
                        )}
                    </Card>
                </main>
            </div>
        </>
    );
}
