import { Head, Link } from '@inertiajs/react';
import { Building2, Plus, UserRoundX } from 'lucide-react';
import DataTable from '@/components/data-table';
import type { DataTableColumn } from '@/components/data-table';
import MemberPage from '@/components/member/member-page';
import StatusBadge from '@/components/member/status-badge';
import { formatNaira } from '@/lib/format';
import { create, index, show } from '@/routes/admin/branches';
import { index as usersIndex } from '@/routes/admin/users';

export type BranchSummary = {
    id: number;
    name: string;
    code: string;
    address: string | null;
    phone: string | null;
    manager: { id: number; name: string } | null;
    isActive: boolean;
};

type BranchRow = BranchSummary & {
    staffCount: number;
    membersCount: number;
    walletBalance: number;
};

export default function BranchesIndex({
    branches,
    unassigned,
    canManage,
}: {
    branches: BranchRow[];
    unassigned: { staff: number; members: number };
    canManage: boolean;
}) {
    const newButton = canManage ? (
        <Link
            href={create()}
            className="inline-flex items-center gap-1.5 rounded-full bg-brand px-3.5 py-1.5 text-sm font-semibold text-white hover:bg-brand-hover"
        >
            <Plus className="size-4" />
            New branch
        </Link>
    ) : undefined;

    const columns: DataTableColumn<BranchRow>[] = [
        {
            key: 'name',
            header: 'Branch',
            sortable: true,
            cell: (branch) => (
                <Link href={show(branch.id)} className="group block min-w-0">
                    <span className="flex items-center gap-1.5 truncate font-semibold text-ink group-hover:text-brand">
                        {branch.name}
                        {!branch.isActive && (
                            <StatusBadge tone="neutral">Inactive</StatusBadge>
                        )}
                    </span>
                    <span className="block truncate text-xs text-ink-400">
                        <span className="font-mono">{branch.code}</span>
                        {branch.address ? ` · ${branch.address}` : ''}
                    </span>
                </Link>
            ),
        },
        {
            key: 'manager',
            header: 'Manager',
            hideOnMobile: true,
            className: 'text-sm text-ink-700',
            cell: (branch) => branch.manager?.name ?? '—',
        },
        {
            key: 'staffCount',
            header: 'Staff',
            sortable: true,
            align: 'right',
            hideOnMobile: true,
            className: 'tabular-nums',
            cell: (branch) => branch.staffCount,
        },
        {
            key: 'membersCount',
            header: 'Members',
            sortable: true,
            align: 'right',
            className: 'tabular-nums',
            cell: (branch) => branch.membersCount,
        },
        {
            key: 'walletBalance',
            header: 'Money held',
            sortable: true,
            align: 'right',
            className: 'font-semibold whitespace-nowrap text-ink tabular-nums',
            cell: (branch) => formatNaira(branch.walletBalance),
        },
    ];

    const hasUnassigned = unassigned.staff + unassigned.members > 0;

    return (
        <>
            <Head title="Branches" />

            <MemberPage
                title="Branches"
                description="Every office with its staff, members and money, seen from head office."
                actions={newButton}
            >
                {hasUnassigned && (
                    <section className="flex flex-wrap items-center gap-3 rounded-landing-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
                        <UserRoundX className="size-5 shrink-0" />
                        <p className="min-w-0 flex-1">
                            {unassigned.members} members and {unassigned.staff}{' '}
                            staff have no branch yet.
                        </p>
                        <Link
                            href={usersIndex({ query: { branch: 'none' } })}
                            className="font-semibold underline-offset-2 hover:underline"
                        >
                            See them
                        </Link>
                    </section>
                )}

                <DataTable
                    title="All branches"
                    description={`${branches.length} ${branches.length === 1 ? 'branch' : 'branches'}`}
                    columns={columns}
                    data={branches}
                    getRowId={(branch) => branch.id}
                    searchable
                    searchPlaceholder="Search name or code"
                    searchText={(branch) =>
                        `${branch.name} ${branch.code} ${branch.address ?? ''}`
                    }
                    empty={{
                        icon: Building2,
                        title: 'No branches yet',
                        description:
                            'Create a branch, choose its manager, then assign staff and members to it.',
                    }}
                />
            </MemberPage>
        </>
    );
}

BranchesIndex.layout = {
    breadcrumbs: [{ title: 'Branches', href: index() }],
};
