import { DataTable, type TableMeta } from '@/components/admin/DataTable';
import { useDataTable } from '@/hooks/useDataTable';
import ClientLayout from '@/Layouts/ClientLayout';
import { PageProps, TenantCard } from '@/types';
import { Head, Link } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useMemo } from 'react';
import { columns } from './components/columns';
import EmptyState from './components/EmptyState';

type Props = PageProps<{
    tenants: TenantCard[];
    createHref: string;
}>;

export default function Dashboard({ tenants, createHref }: Props) {
    const { params, setParams } = useDataTable({
        sort: 'name',
        dir: 'asc',
        filter: 'all',
    });

    const filtered = useMemo(() => {
        let rows = [...tenants];

        // Quick filter
        if (params.filter === 'live')
            rows = rows.filter((t) => t.setupComplete);
        else if (params.filter === 'pending')
            rows = rows.filter((t) => !t.setupComplete);

        // Search
        if (params.search.trim()) {
            const q = params.search.toLowerCase();
            rows = rows.filter(
                (t) =>
                    t.name.toLowerCase().includes(q) ||
                    (t.domain ?? '').toLowerCase().includes(q) ||
                    (t.plan ?? '').toLowerCase().includes(q),
            );
        }

        // Sort
        if (params.sort === 'name') {
            rows.sort((a, b) =>
                params.dir === 'asc'
                    ? a.name.localeCompare(b.name)
                    : b.name.localeCompare(a.name),
            );
        }

        return rows;
    }, [tenants, params.filter, params.search, params.sort, params.dir]);

    const meta: TableMeta = {
        current_page: 1,
        last_page: 1,
        total: filtered.length,
        per_page: filtered.length || 1,
        from: filtered.length ? 1 : 0,
        to: filtered.length,
    };

    const liveCount = tenants.filter((t) => t.setupComplete).length;
    const pendingCount = tenants.filter((t) => !t.setupComplete).length;

    const quickFilters = [
        { label: 'All', value: 'all', count: tenants.length },
        { label: 'Live', value: 'live', count: liveCount },
        { label: 'Setup pending', value: 'pending', count: pendingCount },
    ];

    if (tenants.length === 0) {
        return (
            <ClientLayout title="My Apps">
                <Head title="My Apps" />
                <EmptyState createHref={createHref} />
            </ClientLayout>
        );
    }

    return (
        <ClientLayout title="My Apps">
            <Head title="My Apps" />

            <div className="space-y-6 p-6 lg:p-8">
                <div className="flex items-center justify-between gap-4">
                    <div>
                        <h1 className="text-foreground text-lg font-semibold">
                            My Apps
                        </h1>
                        <p className="text-muted-foreground dark:text-muted-foreground/70 text-sm">
                            {tenants.length}{' '}
                            {tenants.length === 1 ? 'app' : 'apps'} ·{' '}
                            {liveCount} live
                        </p>
                    </div>
                    <Link
                        href={createHref}
                        className="pf-btn flex items-center gap-2 px-4 py-2 text-sm"
                    >
                        <Plus className="h-4 w-4" />
                        New app
                    </Link>
                </div>

                <DataTable
                    columns={columns}
                    data={filtered}
                    meta={meta}
                    params={params}
                    isLoading={false}
                    isFetching={false}
                    onParamsChange={setParams}
                    quickFilters={quickFilters}
                    searchPlaceholder="Search apps…"
                    noun="apps"
                    getRowId={(row) => row.id}
                />
            </div>
        </ClientLayout>
    );
}
