import { Head, Link } from '@inertiajs/react';
import { ArrowRight, MapPin, Pencil, Phone, UsersRound } 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 { formatDate, formatDateTime, formatNaira } from '@/lib/format';
import { cn } from '@/lib/utils';
import { edit, index } from '@/routes/admin/branches';
import { index as transactionsIndex } from '@/routes/admin/transactions';
import { show as userShow } from '@/routes/admin/users';
import type { Paginated, TransactionItem } from '@/types';
import type { BranchSummary } from './index';

type Report = {
    staff: number;
    members: number;
    walletBalance: number;
    savingsBalance: number;
    moneyIn: number;
    moneyOut: number;
    monthLabel: string;
    activeLoans: number;
    pendingLoans: number;
};

type MemberRow = {
    id: number;
    name: string;
    memberId: string;
    phone: string | null;
    membershipStatusLabel: string;
    balance: number;
    joinedAt: string | null;
};

type StaffRow = { id: number; name: string; roles: string[] };

type BranchTransaction = TransactionItem & {
    member: { id: number; name: string };
};

export default function BranchShow({
    branch,
    report,
    staff,
    members,
    transactions,
    canManage,
    canViewLedger,
}: {
    branch: BranchSummary;
    report: Report;
    staff: StaffRow[];
    members: Paginated<MemberRow>;
    transactions: BranchTransaction[];
    canManage: boolean;
    canViewLedger: boolean;
}) {
    const columns: DataTableColumn<MemberRow>[] = [
        {
            key: 'name',
            header: 'Member',
            sortable: true,
            cell: (row) => (
                <Link href={userShow(row.id)} className="group block min-w-0">
                    <span className="block truncate font-semibold text-ink group-hover:text-brand">
                        {row.name}
                    </span>
                    <span className="block font-mono text-xs text-ink-400">
                        {row.memberId}
                    </span>
                </Link>
            ),
        },
        {
            key: 'phone',
            header: 'Phone',
            hideOnMobile: true,
            className: 'text-xs whitespace-nowrap text-ink-500',
            cell: (row) => row.phone ?? '—',
        },
        {
            key: 'membership',
            header: 'Membership',
            hideOnMobile: true,
            cell: (row) => (
                <StatusBadge tone="neutral">
                    {row.membershipStatusLabel}
                </StatusBadge>
            ),
        },
        {
            key: 'balance',
            header: 'Wallet',
            align: 'right',
            className: 'whitespace-nowrap tabular-nums',
            cell: (row) => formatNaira(row.balance),
        },
        {
            key: 'joinedAt',
            header: 'Joined',
            sortable: true,
            hideOnMobile: true,
            className: 'text-xs whitespace-nowrap text-ink-500',
            cell: (row) => formatDate(row.joinedAt),
        },
    ];

    return (
        <>
            <Head title={branch.name} />

            <MemberPage
                title={branch.name}
                description={`${branch.code} · manager: ${branch.manager?.name ?? 'not set'}${branch.isActive ? '' : ' · closed'}`}
                actions={
                    canManage && (
                        <Link
                            href={edit(branch.id)}
                            className="inline-flex items-center gap-1.5 rounded-full border border-surface-200 bg-white px-3.5 py-1.5 text-sm font-semibold text-ink-700 hover:border-brand/40"
                        >
                            <Pencil className="size-4" />
                            Edit branch
                        </Link>
                    )
                }
            >
                {(branch.address || branch.phone) && (
                    <p className="flex flex-wrap gap-x-4 gap-y-1 text-sm text-ink-500">
                        {branch.address && (
                            <span className="flex items-center gap-1.5">
                                <MapPin className="size-4" />
                                {branch.address}
                            </span>
                        )}
                        {branch.phone && (
                            <span className="flex items-center gap-1.5">
                                <Phone className="size-4" />
                                {branch.phone}
                            </span>
                        )}
                    </p>
                )}

                <section className="grid grid-cols-2 gap-3 lg:grid-cols-4">
                    <Stat
                        label="People"
                        value={`${report.members} members`}
                        hint={`${report.staff} staff`}
                    />
                    <Stat
                        label="Money held"
                        value={formatNaira(report.walletBalance)}
                        hint={`${formatNaira(report.savingsBalance)} in savings plans`}
                    />
                    <Stat
                        label={`In · ${report.monthLabel}`}
                        value={formatNaira(report.moneyIn)}
                        hint={`${formatNaira(report.moneyOut)} out`}
                    />
                    <Stat
                        label="Loans"
                        value={`${report.activeLoans} active`}
                        hint={`${report.pendingLoans} under review`}
                    />
                </section>

                <div className="grid gap-5 lg:grid-cols-3">
                    <div className="min-w-0 lg:col-span-2">
                        <DataTable
                            title="Members"
                            description={`${members.total} at this branch`}
                            columns={columns}
                            page={members}
                            getRowId={(row) => row.id}
                            searchable
                            searchPlaceholder="Search name, phone or ADS-ID"
                            defaultSort={{ key: 'name', direction: 'asc' }}
                            empty={{
                                icon: UsersRound,
                                title: 'No members here yet',
                                description:
                                    'Assign members to this branch from their profile.',
                            }}
                        />
                    </div>

                    <section className="h-fit rounded-landing-lg border border-surface-200 bg-white p-5 shadow-landing-sm">
                        <h2 className="font-display text-base font-semibold text-ink">
                            Staff
                        </h2>
                        {staff.length === 0 ? (
                            <p className="mt-2 text-sm text-ink-400">
                                No staff assigned yet.
                            </p>
                        ) : (
                            <ul className="mt-3 divide-y divide-surface-100">
                                {staff.map((person) => (
                                    <li key={person.id} className="py-2">
                                        <Link
                                            href={userShow(person.id)}
                                            className="block truncate text-sm font-semibold text-ink hover:text-brand"
                                        >
                                            {person.name}
                                        </Link>
                                        <span className="block truncate text-xs text-ink-400">
                                            {person.roles.join(', ')}
                                        </span>
                                    </li>
                                ))}
                            </ul>
                        )}
                    </section>
                </div>

                <section className="rounded-landing-lg border border-surface-200 bg-white shadow-landing-sm">
                    <header className="flex items-center justify-between gap-3 border-b border-surface-100 px-5 py-4">
                        <h2 className="font-display text-base font-semibold text-ink">
                            Latest transactions
                        </h2>
                        {canViewLedger && (
                            <Link
                                href={transactionsIndex({
                                    query: { branch: String(branch.id) },
                                })}
                                className="inline-flex items-center gap-1 text-sm font-semibold text-brand hover:text-brand-hover"
                            >
                                Full ledger
                                <ArrowRight className="size-4" />
                            </Link>
                        )}
                    </header>
                    {transactions.length === 0 ? (
                        <p className="px-5 py-6 text-sm text-ink-400">
                            No transactions yet.
                        </p>
                    ) : (
                        <ul className="divide-y divide-surface-100">
                            {transactions.map((transaction) => (
                                <li
                                    key={transaction.id}
                                    className="flex items-center gap-3 px-5 py-3"
                                >
                                    <span className="min-w-0 flex-1">
                                        <span className="block truncate text-sm font-semibold text-ink">
                                            {transaction.member.name} ·{' '}
                                            {transaction.typeLabel}
                                        </span>
                                        <span className="block truncate text-xs text-ink-400">
                                            <span className="font-mono">
                                                {transaction.reference}
                                            </span>{' '}
                                            ·{' '}
                                            {formatDateTime(
                                                transaction.createdAt,
                                            )}
                                        </span>
                                    </span>
                                    <span
                                        className={cn(
                                            'text-sm font-semibold whitespace-nowrap tabular-nums',
                                            transaction.direction === 'credit'
                                                ? 'text-highlight-dark'
                                                : 'text-ink',
                                        )}
                                    >
                                        {transaction.direction === 'credit'
                                            ? '+'
                                            : '−'}
                                        {formatNaira(transaction.amount)}
                                    </span>
                                </li>
                            ))}
                        </ul>
                    )}
                </section>
            </MemberPage>
        </>
    );
}

function Stat({
    label,
    value,
    hint,
}: {
    label: string;
    value: string;
    hint: string;
}) {
    return (
        <section className="min-w-0 rounded-landing-lg border border-surface-200 bg-white p-4 shadow-landing-sm">
            <p className="truncate text-[11px] font-semibold tracking-widest text-ink-400 uppercase">
                {label}
            </p>
            <p className="mt-1 truncate font-display text-xl font-semibold text-ink tabular-nums">
                {value}
            </p>
            <p className="truncate text-xs text-ink-500">{hint}</p>
        </section>
    );
}

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