import { AdminPageHeader, adminLayout } from '@/Layouts/AdminLayout';
import { Card, Input, Pill, Popover, Select } from '@/Components/ui';
import { cn } from '@/lib/cn';
import { Head, Link, router } from '@inertiajs/react';
import { MoreHorizontal, Search } from 'lucide-react';
import {
    useEffect,
    useRef,
    useState,
    type MouseEvent as ReactMouseEvent,
} from 'react';

type TenantRow = {
    id: number;
    name: string;
    users_count: number;
    projects_count: number;
    owner_id: number | null;
    owner_email: string | null;
    plan_key: string;
    created_at: string | null;
};

type PlanOption = { key: string; name: string };

type Paginated<T> = {
    data: T[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    links: Array<{ url: string | null; label: string; active: boolean }>;
};

type Props = {
    tenants: Paginated<TenantRow>;
    filters: { q: string; plan: string };
    plans: PlanOption[];
};

const PLAN_TONES: Record<string, 'accent' | 'neutral'> = {
    pro: 'accent',
    scale: 'accent',
    free: 'neutral',
};

const RELATIVE_FMT = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });

function relativeTime(iso: string | null): string {
    if (!iso) return '—';
    const diffMs = new Date(iso).getTime() - Date.now();
    const absDay = Math.abs(diffMs) / 86_400_000;
    if (absDay < 1) return RELATIVE_FMT.format(Math.round(diffMs / 3_600_000), 'hour');
    if (absDay < 30) return RELATIVE_FMT.format(Math.round(diffMs / 86_400_000), 'day');
    if (absDay < 365) return RELATIVE_FMT.format(Math.round(diffMs / (86_400_000 * 30)), 'month');
    return RELATIVE_FMT.format(Math.round(diffMs / (86_400_000 * 365)), 'year');
}

function planLabel(key: string): string {
    return key.charAt(0).toUpperCase() + key.slice(1);
}

function AdminTenantsIndex({ tenants, filters, plans }: Props) {
    const [q, setQ] = useState(filters.q ?? '');
    const [plan, setPlan] = useState(filters.plan ?? 'all');

    // Debounced auto-apply mirrors the Users page. Skip the first effect so
    // the initial render doesn't refetch the page it just rendered.
    const firstRender = useRef(true);
    useEffect(() => {
        if (firstRender.current) {
            firstRender.current = false;
            return;
        }
        const handle = window.setTimeout(() => {
            const sameQ = q.trim() === (filters.q ?? '');
            const samePlan = plan === (filters.plan ?? 'all');
            if (sameQ && samePlan) return;

            router.get(
                '/admin/tenants',
                {
                    q: q.trim() || undefined,
                    plan: plan === 'all' ? undefined : plan,
                },
                {
                    preserveScroll: true,
                    preserveState: true,
                    replace: true,
                },
            );
        }, 220);
        return () => window.clearTimeout(handle);
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [q, plan]);

    const reset = () => {
        setQ('');
        setPlan('all');
    };

    return (
        <>
            <Head title="Admin · Tenants" />
            <AdminPageHeader
                title="Tenants"
                description="Workspaces in the SaaS deployment."
            />
                <div
                    className="mb-3 flex items-center justify-between text-[11px] text-muted-foreground"
                    data-testid="admin-tenants-summary"
                >
                    <span>
                        {tenants.total === 0
                            ? 'No tenants match these filters.'
                            : `Showing ${tenants.data.length} of ${tenants.total} ${tenants.total === 1 ? 'tenant' : 'tenants'}`}
                    </span>
                </div>

                <form
                    onSubmit={(e) => e.preventDefault()}
                    className="mb-4 flex flex-wrap items-end gap-3"
                    data-testid="admin-tenants-filters"
                >
                    <div className="flex-1 min-w-[220px]">
                        <label
                            htmlFor="tenants-q"
                            className="mb-1 block text-[11px] font-medium text-muted-foreground"
                        >
                            Search
                        </label>
                        <Input
                            id="tenants-q"
                            value={q}
                            onChange={(e) => setQ(e.target.value)}
                            placeholder="Tenant name"
                            leadingIcon={<Search strokeWidth={2} />}
                            data-testid="admin-tenants-q"
                        />
                    </div>
                    <div>
                        <label
                            htmlFor="tenants-plan"
                            className="mb-1 block text-[11px] font-medium text-muted-foreground"
                        >
                            Plan
                        </label>
                        <Select
                            id="tenants-plan"
                            value={plan}
                            onChange={(e) => setPlan(e.target.value)}
                            data-testid="admin-tenants-plan"
                            wrapperClassName="w-40"
                        >
                            <option value="all">Any</option>
                            {plans.map((p) => (
                                <option key={p.key} value={p.key}>
                                    {p.name}
                                </option>
                            ))}
                        </Select>
                    </div>
                    <button
                        type="button"
                        onClick={reset}
                        data-testid="admin-tenants-reset"
                        className="h-10 rounded-md border border-transparent px-3 text-[12px] font-medium text-muted-foreground transition-colors hover:text-foreground"
                    >
                        Reset
                    </button>
                </form>

                <Card padding="none" className="overflow-hidden">
                    <table className="stagger-rows w-full text-sm">
                        <thead className="border-b border-border bg-muted/30">
                            <tr className="text-left text-[11px] font-medium text-muted-foreground">
                                <th className="px-4 py-2.5">Name</th>
                                <th className="px-4 py-2.5">Owner</th>
                                <th className="px-4 py-2.5">Plan</th>
                                <th className="px-4 py-2.5 text-right">Users</th>
                                <th className="px-4 py-2.5 text-right">
                                    Projects
                                </th>
                                <th className="px-4 py-2.5">Created</th>
                                <th className="px-4 py-2.5 w-12" />
                            </tr>
                        </thead>
                        <tbody>
                            {tenants.data.length === 0 ? (
                                <tr>
                                    <td
                                        colSpan={7}
                                        className="px-4 py-12 text-center text-sm text-muted-foreground"
                                        data-testid="admin-tenants-empty"
                                    >
                                        No tenants match.
                                    </td>
                                </tr>
                            ) : (
                                tenants.data.map((t) => (
                                    <tr
                                        key={t.id}
                                        className="border-b border-border/60 last:border-0"
                                        data-testid={`admin-tenant-row-${t.id}`}
                                    >
                                        <td className="px-4 py-3">
                                            <Link
                                                href={`/admin/tenants/${t.id}`}
                                                className="font-medium text-foreground hover:text-accent"
                                                data-testid={`admin-tenant-link-${t.id}`}
                                            >
                                                {t.name}
                                            </Link>
                                        </td>
                                        <td className="px-4 py-3 font-mono text-[12px] text-foreground/80">
                                            {t.owner_email ?? (
                                                <span className="text-muted-foreground">—</span>
                                            )}
                                        </td>
                                        <td className="px-4 py-3">
                                            <Pill
                                                tone={PLAN_TONES[t.plan_key] ?? 'neutral'}
                                                size="sm"
                                            >
                                                {planLabel(t.plan_key)}
                                            </Pill>
                                        </td>
                                        <td className="px-4 py-3 text-right tabular-nums text-foreground/80">
                                            {t.users_count}
                                        </td>
                                        <td className="px-4 py-3 text-right tabular-nums text-foreground/80">
                                            {t.projects_count}
                                        </td>
                                        <td className="px-4 py-3 text-[12px] text-muted-foreground">
                                            {relativeTime(t.created_at)}
                                        </td>
                                        <td className="px-4 py-3">
                                            <RowMenu tenant={t} />
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </Card>

                {tenants.last_page > 1 && (
                    <nav
                        className="mt-4 flex items-center justify-between"
                        data-testid="admin-tenants-pagination"
                    >
                        <span className="text-[11px] text-muted-foreground">
                            Page {tenants.current_page} of {tenants.last_page} ·{' '}
                            {tenants.total} total
                        </span>
                        <div className="flex flex-wrap gap-1">
                            {tenants.links.map((link, i) => (
                                <button
                                    key={`${link.label}-${i}`}
                                    type="button"
                                    disabled={!link.url}
                                    onClick={() =>
                                        link.url && router.visit(link.url)
                                    }
                                    className={cn(
                                        'rounded-md border border-border px-2.5 py-1 text-[11px] font-medium transition-colors disabled:opacity-40',
                                        link.active
                                            ? 'border-accent/40 bg-accent/5 text-accent'
                                            : 'text-muted-foreground hover:bg-muted hover:text-foreground',
                                    )}
                                    dangerouslySetInnerHTML={{
                                        __html: link.label,
                                    }}
                                />
                            ))}
                        </div>
                    </nav>
                )}
        </>
    );
}

AdminTenantsIndex.layout = adminLayout;

export default AdminTenantsIndex;

function RowMenu({ tenant }: { tenant: TenantRow }) {
    const stop = (e: ReactMouseEvent) => {
        e.preventDefault();
        e.stopPropagation();
    };
    const ownerHref = tenant.owner_id !== null
        ? `/admin/users/${tenant.owner_id}`
        : null;

    return (
        <div onClick={stop} onMouseDown={stop} className="flex justify-end">
            <Popover
                align="end"
                trigger={({ open, toggle }) => (
                    <button
                        type="button"
                        onClick={toggle}
                        aria-label="Tenant actions"
                        aria-expanded={open}
                        data-testid={`admin-tenant-menu-${tenant.id}`}
                        className={cn(
                            'inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground',
                            open && 'bg-muted text-foreground',
                        )}
                    >
                        <MoreHorizontal className="h-4 w-4" strokeWidth={2} />
                    </button>
                )}
            >
                <div className="flex min-w-[180px] flex-col">
                    <Link
                        href={`/admin/tenants/${tenant.id}`}
                        data-testid={`admin-tenant-view-detail-${tenant.id}`}
                        className="rounded-md px-2 py-1.5 text-left text-sm text-foreground hover:bg-muted"
                    >
                        View tenant detail
                    </Link>
                    {ownerHref ? (
                        <Link
                            href={ownerHref}
                            data-testid={`admin-tenant-view-owner-${tenant.id}`}
                            className="rounded-md px-2 py-1.5 text-left text-sm text-foreground hover:bg-muted"
                        >
                            View owner
                        </Link>
                    ) : (
                        <span
                            className="rounded-md px-2 py-1.5 text-left text-sm text-muted-foreground"
                            data-testid={`admin-tenant-no-owner-${tenant.id}`}
                        >
                            No owner on file
                        </span>
                    )}
                </div>
            </Popover>
        </div>
    );
}
