import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import PlatformLayout from '@/layouts/platform-layout';
import { timeAgo } from '@/lib/format';
import { cn } from '@/lib/utils';
import { Link, router } from '@inertiajs/react';
import { FormEventHandler, useState } from 'react';

interface TenantRow {
    id: number;
    name: string;
    subdomain: string;
    status: string;
    plan: string | null;
    subscription_status: string | null;
    seats: number | null;
    users_count: number;
    tickets_count: number;
    created_at: string;
}

interface Props {
    tenants: { data: TenantRow[]; links: { url: string | null; label: string; active: boolean }[]; total: number };
    filters: { search: string; status: string | null };
}

export const tenantStatusClass: Record<string, string> = {
    trial: 'border-sky-300 text-sky-800 dark:text-sky-300',
    active: 'border-emerald-300 text-emerald-800 dark:text-emerald-300',
    suspended: 'border-red-300 bg-red-50 text-red-800 dark:bg-red-950/40 dark:text-red-300',
};

export default function TenantsIndex({ tenants, filters }: Props) {
    const [search, setSearch] = useState(filters.search);

    const apply = (next: Partial<Props['filters']>) =>
        router.get('/tenants', { ...filters, search, ...next }, { preserveState: true, preserveScroll: true, replace: true });

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        apply({ search });
    };

    return (
        <PlatformLayout title="Tenants">
            <div className="flex flex-wrap items-center gap-3">
                <h1 className="mr-auto text-xl font-semibold">
                    Tenants <span className="text-muted-foreground text-base font-normal">({tenants.total})</span>
                </h1>
                <form onSubmit={submit}>
                    <Input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Name, subdomain or owner email" className="bg-background w-72" />
                </form>
                <select
                    value={filters.status ?? ''}
                    onChange={(e) => apply({ status: e.target.value || null })}
                    className="border-input bg-background h-9 rounded-md border px-2 text-sm"
                    aria-label="Filter by status"
                >
                    <option value="">All statuses</option>
                    <option value="trial">Trial</option>
                    <option value="active">Active</option>
                    <option value="suspended">Suspended</option>
                </select>
            </div>

            <div className="bg-background overflow-x-auto rounded-lg border">
                <table className="w-full text-sm">
                    <thead className="bg-muted/50 text-muted-foreground text-left text-xs">
                        <tr>
                            <th className="px-4 py-2 font-medium">Company</th>
                            <th className="px-4 py-2 font-medium">Status</th>
                            <th className="px-4 py-2 font-medium">Plan</th>
                            <th className="px-4 py-2 text-right font-medium">Seats</th>
                            <th className="px-4 py-2 text-right font-medium">Users</th>
                            <th className="px-4 py-2 text-right font-medium">Tickets</th>
                            <th className="px-4 py-2 font-medium">Signed up</th>
                        </tr>
                    </thead>
                    <tbody>
                        {tenants.data.length === 0 && (
                            <tr>
                                <td colSpan={7} className="text-muted-foreground px-4 py-10 text-center">
                                    No tenants match.
                                </td>
                            </tr>
                        )}
                        {tenants.data.map((t) => (
                            <tr key={t.id} className="hover:bg-muted/40 border-t">
                                <td className="px-4 py-2.5">
                                    <Link href={`/tenants/${t.id}`} className="font-medium hover:underline">
                                        {t.name}
                                    </Link>
                                    <div className="text-muted-foreground text-xs">{t.subdomain}</div>
                                </td>
                                <td className="px-4 py-2.5">
                                    <Badge variant="outline" className={cn('capitalize', tenantStatusClass[t.status])}>
                                        {t.status}
                                    </Badge>
                                </td>
                                <td className="px-4 py-2.5">
                                    {t.plan} <span className="text-muted-foreground text-xs">({t.subscription_status})</span>
                                </td>
                                <td className="px-4 py-2.5 text-right tabular-nums">{t.seats}</td>
                                <td className="px-4 py-2.5 text-right tabular-nums">{t.users_count}</td>
                                <td className="px-4 py-2.5 text-right tabular-nums">{t.tickets_count}</td>
                                <td className="text-muted-foreground px-4 py-2.5 text-xs">{timeAgo(t.created_at)}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>

            {tenants.links.length > 3 && (
                <nav className="flex flex-wrap gap-1" aria-label="Pagination">
                    {tenants.links.map((l, i) =>
                        l.url ? (
                            <Link
                                key={i}
                                href={l.url}
                                preserveScroll
                                className={cn('rounded border px-3 py-1 text-sm', l.active ? 'bg-primary text-primary-foreground' : 'bg-background')}
                                dangerouslySetInnerHTML={{ __html: l.label }}
                            />
                        ) : (
                            <span key={i} className="text-muted-foreground rounded border px-3 py-1 text-sm" dangerouslySetInnerHTML={{ __html: l.label }} />
                        ),
                    )}
                </nav>
            )}
        </PlatformLayout>
    );
}
