import { Head, Link, router } from '@inertiajs/react';
import type { LucideIcon } from 'lucide-react';
import {
    ArrowDownLeft,
    ArrowUpRight,
    ChevronDown,
    ExternalLink,
    FileText,
    HandCoins,
    History,
    LifeBuoy,
    Pencil,
    PiggyBank,
    ShieldCheck,
    UserRoundPen,
    Wallet,
} from 'lucide-react';
import type { ReactNode } from 'react';
import DataTable from '@/components/data-table';
import type { DataTableColumn } from '@/components/data-table';
import MemberImages from '@/components/member/member-images';
import MemberPage from '@/components/member/member-page';
import ProgressBar from '@/components/member/progress-bar';
import StatusBadge from '@/components/member/status-badge';
import type { BadgeTone } from '@/components/member/status-badge';
import { useInitials } from '@/hooks/use-initials';
import { formatDate, formatDateTime, formatNaira } from '@/lib/format';
import { cn } from '@/lib/utils';
import { show as financingShow } from '@/routes/admin/financing';
import { show as groupShow } from '@/routes/admin/groups';
import { show as ticketShow } from '@/routes/admin/support';
import { edit as editDetails } from '@/routes/admin/users/details';
import { store as storeMemberImage } from '@/routes/admin/users/images';
import { edit, index, statement as statementRoute } from '@/routes/admin/users';
import { show as receiptShow } from '@/routes/receipts';
import { file } from '@/routes/kyc/documents';
import type { Paginated, SelectOption, TransactionItem } from '@/types';

type Profile = {
    id: number;
    memberId: string;
    photoUrl: string | null;
    signatureUrl: string | null;
    gender: string | null;
    occupation: string | null;
    idNumber: string | null;
    nextOfKin: { name: string; phone: string; relationship: string } | null;
    membershipStatus: string;
    membershipStatusLabel: string;
    branch: { id: number; name: string; code: string } | null;
    groups: { id: number; name: string }[];
    name: string;
    email: string;
    phone: string | null;
    dateOfBirth: string | null;
    address: string | null;
    kycStatus: string;
    kycStatusLabel: string;
    kycVerifiedAt: string | null;
    emailVerified: boolean;
    hasPin: boolean;
    roles: string[];
    joinedAt: string | null;
    canEdit: boolean;
};

type Plan = {
    id: number;
    name: string;
    typeLabel: string;
    balance: number;
    targetAmount: number;
    progress: number;
    status: string;
};

type FinancingRow = {
    id: number;
    reference: string;
    typeLabel: string;
    amountRequested: number;
    approvedAmount: number | null;
    status: string;
    statusLabel: string;
    appliedAt: string | null;
};

type DocumentRow = {
    id: number;
    typeLabel: string;
    status: string;
    statusLabel: string;
    originalName: string;
    rejectionReason: string | null;
    uploadedAt: string | null;
};

type TicketRow = {
    id: number;
    reference: string;
    subject: string;
    status: string;
    statusLabel: string;
    lastActivityAt: string | null;
};

const tones: Record<string, BadgeTone> = {
    verified: 'success',
    approved: 'success',
    active: 'info',
    completed: 'success',
    success: 'success',
    resolved: 'success',
    pending: 'pending',
    open: 'pending',
    awaiting_member: 'info',
    rejected: 'failed',
    declined: 'failed',
    failed: 'failed',
};

const cardClasses =
    'min-w-0 rounded-landing-lg border border-surface-200 bg-white shadow-landing-sm';

export default function UserShow({
    user,
    wallet,
    totals,
    transactions,
    transactionTypes,
    savingsPlans,
    financings,
    kycDocuments,
    tickets,
    can,
}: {
    user: Profile;
    wallet: {
        accountNumber: string;
        balance: number;
        openedAt: string | null;
    } | null;
    totals: { moneyIn: number; moneyOut: number; entries: number };
    transactions: Paginated<TransactionItem>;
    transactionTypes: SelectOption[];
    savingsPlans: Plan[];
    financings: FinancingRow[];
    kycDocuments: DocumentRow[];
    tickets: TicketRow[];
    can: {
        editDetails: boolean;
        viewDocuments: boolean;
        viewLoans: boolean;
        viewTickets: boolean;
    };
}) {
    const getInitials = useInitials();
    const typeFilter =
        typeof window === 'undefined'
            ? ''
            : (new URLSearchParams(window.location.search).get('type') ?? '');
    const savingsTotal = savingsPlans
        .filter((plan) => plan.status !== 'closed')
        .reduce((sum, plan) => sum + plan.balance, 0);

    const filterByType = (type: string) => {
        const query = new URLSearchParams(window.location.search);

        if (type) {
            query.set('type', type);
        } else {
            query.delete('type');
        }

        query.delete('page');
        router.get(
            `${window.location.pathname}${query.toString() ? `?${query}` : ''}`,
            {},
            { preserveState: true, preserveScroll: true, replace: true },
        );
    };

    const transactionColumns: DataTableColumn<TransactionItem>[] = [
        {
            key: 'description',
            header: 'Transaction',
            cell: (transaction) => {
                const isCredit = transaction.direction === 'credit';

                return (
                    <span className="flex min-w-0 items-center gap-3">
                        <span
                            className={cn(
                                'flex size-8 shrink-0 items-center justify-center rounded-full',
                                isCredit
                                    ? 'bg-highlight-faint text-highlight-dark'
                                    : 'bg-surface-100 text-ink-500',
                            )}
                        >
                            {isCredit ? (
                                <ArrowDownLeft className="size-4" />
                            ) : (
                                <ArrowUpRight className="size-4" />
                            )}
                        </span>
                        <span className="min-w-0">
                            <span className="block max-w-64 truncate font-medium text-ink">
                                {transaction.description}
                            </span>
                            <span className="block truncate text-xs text-ink-400">
                                {transaction.typeLabel} ·{' '}
                                <Link
                                    href={receiptShow(transaction.id)}
                                    className="hover:text-brand"
                                >
                                    {transaction.reference}
                                </Link>
                            </span>
                        </span>
                    </span>
                );
            },
        },
        {
            key: 'createdAt',
            header: 'Date',
            sortable: true,
            hideOnMobile: true,
            className: 'text-xs whitespace-nowrap text-ink-500',
            cell: (transaction) => formatDateTime(transaction.createdAt),
        },
        {
            key: 'status',
            header: 'Status',
            hideOnMobile: true,
            cell: (transaction) => (
                <StatusBadge tone={tones[transaction.status] ?? 'neutral'}>
                    {transaction.statusLabel}
                </StatusBadge>
            ),
        },
        {
            key: 'amount',
            header: 'Amount',
            sortable: true,
            align: 'right',
            className: 'whitespace-nowrap tabular-nums',
            cell: (transaction) => (
                <span
                    className={cn(
                        'font-semibold',
                        transaction.direction === 'credit'
                            ? 'text-highlight-dark'
                            : 'text-ink',
                    )}
                >
                    {transaction.direction === 'credit' ? '+' : '−'}
                    {formatNaira(transaction.amount)}
                </span>
            ),
        },
        {
            key: 'balanceAfter',
            header: 'Balance after',
            align: 'right',
            hideOnMobile: true,
            className: 'text-xs whitespace-nowrap text-ink-500 tabular-nums',
            cell: (transaction) =>
                transaction.balanceAfter === null
                    ? '—'
                    : formatNaira(transaction.balanceAfter),
        },
    ];

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

            <MemberPage
                title={user.name}
                description={`${user.email} · joined ${formatDate(user.joinedAt)}`}
                actions={
                    <>
                        <Link
                            href={statementRoute(user.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"
                        >
                            <FileText className="size-4" />
                            Statement
                        </Link>
                        {can.editDetails && (
                            <Link
                                href={editDetails(user.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"
                            >
                                <UserRoundPen className="size-4" />
                                Edit details
                            </Link>
                        )}
                        {user.canEdit && (
                            <Link
                                href={edit(user.id)}
                                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"
                            >
                                <Pencil className="size-4" />
                                Change role
                            </Link>
                        )}
                    </>
                }
            >
                <div className="grid gap-4 lg:grid-cols-3">
                    <section className={cn(cardClasses, 'p-5 lg:col-span-2')}>
                        <div className="flex flex-wrap items-center gap-4">
                            {user.photoUrl ? (
                                <img
                                    src={user.photoUrl}
                                    alt={`Photo of ${user.name}`}
                                    className="size-14 shrink-0 rounded-full object-cover"
                                />
                            ) : (
                                <span className="flex size-14 shrink-0 items-center justify-center rounded-full bg-brand text-lg font-semibold text-white">
                                    {getInitials(user.name)}
                                </span>
                            )}
                            <div className="min-w-0 flex-1">
                                <div className="flex flex-wrap items-center gap-1.5">
                                    {user.roles.length > 0 ? (
                                        user.roles.map((role) => (
                                            <StatusBadge key={role} tone="info">
                                                {role}
                                            </StatusBadge>
                                        ))
                                    ) : (
                                        <StatusBadge tone="neutral">
                                            Member
                                        </StatusBadge>
                                    )}
                                    <StatusBadge
                                        tone={
                                            tones[user.kycStatus] ?? 'neutral'
                                        }
                                    >
                                        <ShieldCheck className="mr-1 size-3" />
                                        {user.kycStatusLabel}
                                    </StatusBadge>
                                </div>
                                <p className="mt-1 text-xs text-ink-400">
                                    Membership ID{' '}
                                    <span className="font-mono font-semibold text-ink-700">
                                        {user.memberId}
                                    </span>
                                </p>
                            </div>
                        </div>
                        <dl className="mt-5 grid gap-x-6 gap-y-3 text-sm sm:grid-cols-2">
                            <Detail term="Email">
                                {user.email}{' '}
                                <span className="text-xs text-ink-400">
                                    {user.emailVerified
                                        ? '· verified'
                                        : '· not verified'}
                                </span>
                            </Detail>
                            <Detail term="Phone">{user.phone ?? '—'}</Detail>
                            <Detail term="Date of birth">
                                {user.dateOfBirth
                                    ? formatDate(user.dateOfBirth)
                                    : '—'}
                            </Detail>
                            <Detail term="Transaction PIN">
                                {user.hasPin ? 'Set' : 'Not set'}
                            </Detail>
                            <Detail term="Identity verified">
                                {user.kycVerifiedAt
                                    ? formatDate(user.kycVerifiedAt)
                                    : 'Not yet'}
                            </Detail>
                            <Detail term="Branch">
                                {user.branch
                                    ? `${user.branch.name} (${user.branch.code})`
                                    : '—'}
                            </Detail>
                            <Detail term="Smart Save groups">
                                {user.groups.length > 0
                                    ? user.groups.map((group, position) => (
                                          <span key={group.id}>
                                              {position > 0 && ', '}
                                              <Link
                                                  href={groupShow(group.id)}
                                                  className="hover:text-brand"
                                              >
                                                  {group.name}
                                              </Link>
                                          </span>
                                      ))
                                    : '—'}
                            </Detail>
                            <Detail term="Gender">{user.gender ?? '—'}</Detail>
                            <Detail term="Occupation">
                                {user.occupation ?? '—'}
                            </Detail>
                            <Detail term="Identification number">
                                {user.idNumber ?? '—'}
                            </Detail>
                            <Detail term="Next of kin">
                                {user.nextOfKin
                                    ? `${user.nextOfKin.name} (${user.nextOfKin.relationship}) · ${user.nextOfKin.phone}`
                                    : '—'}
                            </Detail>
                            <Detail term="Address">
                                {user.address ?? '—'}
                            </Detail>
                        </dl>
                    </section>

                    <section className="relative overflow-hidden rounded-landing-lg bg-linear-to-br from-brand to-brand-dark p-5 text-white shadow-landing">
                        <p className="flex items-center gap-1.5 text-sm text-white/70">
                            <Wallet className="size-4" />
                            Wallet balance
                        </p>
                        <p className="mt-1 font-display text-2xl font-semibold tabular-nums">
                            {wallet ? formatNaira(wallet.balance) : '—'}
                        </p>
                        <p className="mt-1 text-xs text-white/60">
                            {wallet
                                ? `Account ${wallet.accountNumber}`
                                : 'No wallet opened yet'}
                        </p>
                        <dl className="mt-4 grid grid-cols-2 gap-2 text-xs">
                            <div className="rounded-landing bg-white/8 px-3 py-2 ring-1 ring-white/10">
                                <dt className="text-white/60">Money in</dt>
                                <dd className="mt-0.5 truncate text-sm font-semibold tabular-nums">
                                    {formatNaira(totals.moneyIn)}
                                </dd>
                            </div>
                            <div className="rounded-landing bg-white/8 px-3 py-2 ring-1 ring-white/10">
                                <dt className="text-white/60">Money out</dt>
                                <dd className="mt-0.5 truncate text-sm font-semibold tabular-nums">
                                    {formatNaira(totals.moneyOut)}
                                </dd>
                            </div>
                            <div className="rounded-landing bg-white/8 px-3 py-2 ring-1 ring-white/10">
                                <dt className="text-white/60">In savings</dt>
                                <dd className="mt-0.5 truncate text-sm font-semibold tabular-nums">
                                    {formatNaira(savingsTotal)}
                                </dd>
                            </div>
                            <div className="rounded-landing bg-white/8 px-3 py-2 ring-1 ring-white/10">
                                <dt className="text-white/60">Transactions</dt>
                                <dd className="mt-0.5 text-sm font-semibold tabular-nums">
                                    {totals.entries}
                                </dd>
                            </div>
                        </dl>
                    </section>
                </div>

                <section className={cn(cardClasses, 'p-5')}>
                    <h2 className="mb-3 font-display text-base font-semibold text-ink">
                        Photo and signature
                    </h2>
                    <MemberImages
                        photoUrl={user.photoUrl}
                        signatureUrl={user.signatureUrl}
                        uploadUrl={
                            can.editDetails
                                ? (kind) =>
                                      storeMemberImage.url({
                                          user: user.id,
                                          image: kind,
                                      })
                                : undefined
                        }
                    />
                </section>

                <div className="grid gap-4 lg:grid-cols-2">
                    <ListCard
                        icon={PiggyBank}
                        title="Savings plans"
                        count={savingsPlans.length}
                        empty="No savings plans."
                    >
                        {savingsPlans.map((plan) => (
                            <li key={plan.id} className="px-4 py-3">
                                <div className="flex items-center gap-2">
                                    <span className="min-w-0 flex-1">
                                        <span className="block truncate text-sm font-semibold text-ink">
                                            {plan.name}
                                        </span>
                                        <span className="block text-xs text-ink-400">
                                            {plan.typeLabel}
                                        </span>
                                    </span>
                                    <span className="text-right text-sm font-semibold text-ink tabular-nums">
                                        {formatNaira(plan.balance)}
                                        <span className="block text-xs font-normal text-ink-400">
                                            of {formatNaira(plan.targetAmount)}
                                        </span>
                                    </span>
                                </div>
                                <div className="mt-2 flex items-center gap-2">
                                    <div className="flex-1">
                                        <ProgressBar
                                            value={plan.progress}
                                            label={`${plan.name} progress`}
                                        />
                                    </div>
                                    {plan.status === 'closed' && (
                                        <StatusBadge tone="neutral">
                                            Closed
                                        </StatusBadge>
                                    )}
                                </div>
                            </li>
                        ))}
                    </ListCard>

                    <ListCard
                        icon={HandCoins}
                        title="Financing"
                        count={financings.length}
                        empty="No financing applications."
                    >
                        {financings.map((financing) => {
                            const content = (
                                <>
                                    <span className="min-w-0 flex-1">
                                        <span className="block truncate text-sm font-semibold text-ink">
                                            {financing.typeLabel}
                                        </span>
                                        <span className="block truncate text-xs text-ink-400">
                                            {financing.reference} · applied{' '}
                                            {formatDate(financing.appliedAt)}
                                        </span>
                                    </span>
                                    <span className="text-right">
                                        <span className="block text-sm font-semibold text-ink tabular-nums">
                                            {formatNaira(
                                                financing.approvedAmount ??
                                                    financing.amountRequested,
                                            )}
                                        </span>
                                        <StatusBadge
                                            tone={
                                                tones[financing.status] ??
                                                'neutral'
                                            }
                                        >
                                            {financing.statusLabel}
                                        </StatusBadge>
                                    </span>
                                </>
                            );

                            return (
                                <li key={financing.id}>
                                    {can.viewLoans ? (
                                        <Link
                                            href={financingShow(financing.id)}
                                            className="flex items-center gap-3 px-4 py-3 hover:bg-surface-50"
                                        >
                                            {content}
                                        </Link>
                                    ) : (
                                        <div className="flex items-center gap-3 px-4 py-3">
                                            {content}
                                        </div>
                                    )}
                                </li>
                            );
                        })}
                    </ListCard>

                    <ListCard
                        icon={FileText}
                        title="Verification documents"
                        count={kycDocuments.length}
                        empty="No documents uploaded."
                    >
                        {kycDocuments.map((document) => (
                            <li
                                key={document.id}
                                className="flex items-center gap-3 px-4 py-3"
                            >
                                <span className="min-w-0 flex-1">
                                    <span className="block truncate text-sm font-semibold text-ink">
                                        {document.typeLabel}
                                    </span>
                                    <span className="block truncate text-xs text-ink-400">
                                        {document.rejectionReason ??
                                            `${document.originalName} · ${formatDate(document.uploadedAt)}`}
                                    </span>
                                </span>
                                <StatusBadge
                                    tone={tones[document.status] ?? 'neutral'}
                                >
                                    {document.statusLabel}
                                </StatusBadge>
                                {can.viewDocuments && (
                                    <a
                                        href={file.url(document.id)}
                                        target="_blank"
                                        rel="noopener"
                                        className="rounded-full p-1.5 text-ink-400 hover:bg-brand-faint hover:text-brand"
                                        aria-label={`Open ${document.typeLabel}`}
                                    >
                                        <ExternalLink className="size-3.5" />
                                    </a>
                                )}
                            </li>
                        ))}
                    </ListCard>

                    <ListCard
                        icon={LifeBuoy}
                        title="Support tickets"
                        count={tickets.length}
                        empty="No support tickets."
                    >
                        {tickets.map((ticket) => {
                            const content = (
                                <>
                                    <span className="min-w-0 flex-1">
                                        <span className="block truncate text-sm font-semibold text-ink">
                                            {ticket.subject}
                                        </span>
                                        <span className="block truncate text-xs text-ink-400">
                                            {ticket.reference} ·{' '}
                                            {formatDate(ticket.lastActivityAt)}
                                        </span>
                                    </span>
                                    <StatusBadge
                                        tone={tones[ticket.status] ?? 'neutral'}
                                    >
                                        {ticket.statusLabel}
                                    </StatusBadge>
                                </>
                            );

                            return (
                                <li key={ticket.id}>
                                    {can.viewTickets ? (
                                        <Link
                                            href={ticketShow(ticket.id)}
                                            className="flex items-center gap-3 px-4 py-3 hover:bg-surface-50"
                                        >
                                            {content}
                                        </Link>
                                    ) : (
                                        <div className="flex items-center gap-3 px-4 py-3">
                                            {content}
                                        </div>
                                    )}
                                </li>
                            );
                        })}
                    </ListCard>
                </div>

                <DataTable
                    title={
                        <span className="flex items-center gap-2">
                            <History className="size-4 text-ink-400" />
                            Transactions
                        </span>
                    }
                    description={`${transactions.total} ${transactions.total === 1 ? 'entry' : 'entries'}`}
                    columns={transactionColumns}
                    page={transactions}
                    getRowId={(transaction) => transaction.id}
                    searchable
                    searchPlaceholder="Search reference or description"
                    defaultSort={{ key: 'createdAt', direction: 'desc' }}
                    toolbar={
                        <div className="relative w-full sm:w-auto">
                            <select
                                value={typeFilter}
                                onChange={(event) =>
                                    filterByType(event.target.value)
                                }
                                aria-label="Filter by type"
                                className="h-9 w-full appearance-none rounded-md border border-input bg-white pr-8 pl-3 text-sm text-ink shadow-xs outline-none focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15 sm:w-48"
                            >
                                <option value="">All types</option>
                                {transactionTypes.map((type) => (
                                    <option key={type.value} value={type.value}>
                                        {type.label}
                                    </option>
                                ))}
                            </select>
                            <ChevronDown className="pointer-events-none absolute top-1/2 right-2.5 size-4 -translate-y-1/2 text-ink-400" />
                        </div>
                    }
                    empty={{
                        icon: History,
                        title: 'No transactions yet',
                        description:
                            'Money moving in or out of this wallet will appear here.',
                    }}
                />
            </MemberPage>
        </>
    );
}

function Detail({ term, children }: { term: string; children: ReactNode }) {
    return (
        <div className="min-w-0">
            <dt className="text-xs text-ink-400">{term}</dt>
            <dd className="mt-0.5 font-medium wrap-break-word text-ink">
                {children}
            </dd>
        </div>
    );
}

function ListCard({
    icon: Icon,
    title,
    count,
    empty,
    children,
}: {
    icon: LucideIcon;
    title: string;
    count: number;
    empty: string;
    children: ReactNode;
}) {
    return (
        <section className={cn(cardClasses, 'overflow-hidden')}>
            <h2 className="flex items-center gap-2 border-b border-surface-100 px-4 py-3 font-display text-base font-semibold text-ink">
                <Icon className="size-4 text-ink-400" />
                {title}
                <span className="ml-auto font-body text-xs font-normal text-ink-400">
                    {count}
                </span>
            </h2>
            {count === 0 ? (
                <p className="px-4 py-8 text-center text-sm text-ink-400">
                    {empty}
                </p>
            ) : (
                <ul className="max-h-80 divide-y divide-surface-100 overflow-y-auto">
                    {children}
                </ul>
            )}
        </section>
    );
}

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