import { Head } from '@inertiajs/react';
import { History } 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 ReportToolbar from '@/components/report-toolbar';
import { formatDateTime } from '@/lib/format';
import { auditTrail } from '@/routes/admin';
import type { Paginated, SelectOption } from '@/types';

type Row = {
    id: number;
    action: string;
    subjectType: string | null;
    subject: string | null;
    reference: string | null;
    details: Record<string, unknown> | null;
    ipAddress: string | null;
    device: string | null;
    at: string | null;
    actor: { id: number | null; name: string };
    account: { id: number; name: string; memberId: string } | null;
};

const actions: Record<
    string,
    { label: string; tone: 'success' | 'failed' | 'neutral' | 'pending' }
> = {
    created: { label: 'Created', tone: 'success' },
    updated: { label: 'Changed', tone: 'neutral' },
    deleted: { label: 'Deleted', tone: 'failed' },
    role_changed: { label: 'Role changed', tone: 'pending' },
    permissions_changed: { label: 'Permissions changed', tone: 'pending' },
};

const actionOptions: SelectOption[] = Object.entries(actions).map(
    ([value, meta]) => ({ value, label: meta.label }),
);

function show(value: unknown): string {
    if (value === null || value === undefined || value === '') {
        return '—';
    }

    if (Array.isArray(value)) {
        return value.length ? value.map(show).join(', ') : 'none';
    }

    if (typeof value === 'object') {
        return JSON.stringify(value);
    }

    return typeof value === 'string' ? value : JSON.stringify(value);
}

function isChange(value: unknown): value is { from: unknown; to: unknown } {
    return (
        typeof value === 'object' &&
        value !== null &&
        'from' in value &&
        'to' in value
    );
}

function Details({ details }: { details: Row['details'] }) {
    if (!details) {
        return <span className="text-ink-400">—</span>;
    }

    const lines = Object.entries(details).map(([key, value]) => (
        <li key={key} className="break-words">
            <span className="font-medium text-ink-700">
                {key.replaceAll('_', ' ')}
            </span>
            {': '}
            {isChange(value) ? (
                <>
                    <span className="text-ink-400 line-through">
                        {show(value.from)}
                    </span>{' '}
                    → {show(value.to)}
                </>
            ) : (
                show(value)
            )}
        </li>
    ));

    if (lines.length <= 3) {
        return <ul className="grid gap-0.5">{lines}</ul>;
    }

    return (
        <details>
            <summary className="cursor-pointer text-brand">
                {lines.length} fields
            </summary>
            <ul className="mt-1 grid gap-0.5">{lines}</ul>
        </details>
    );
}

export default function AuditTrail({
    entries,
    filters,
    types,
    todayCount,
}: {
    entries: Paginated<Row>;
    filters: {
        action: string;
        type: string;
        from: string | null;
        to: string | null;
    };
    types: SelectOption[];
    todayCount: number;
}) {
    const columns: DataTableColumn<Row>[] = [
        {
            key: 'at',
            header: 'When',
            className: 'text-xs whitespace-nowrap text-ink-500',
            cell: (row) => formatDateTime(row.at),
        },
        {
            key: 'actor',
            header: 'Who',
            cell: (row) => (
                <span className="block min-w-0">
                    <span className="block truncate font-semibold text-ink">
                        {row.actor.name}
                    </span>
                    <span className="block truncate text-xs text-ink-400">
                        {[row.ipAddress, row.device]
                            .filter(Boolean)
                            .join(' · ') || 'Scheduled job'}
                    </span>
                </span>
            ),
        },
        {
            key: 'action',
            header: 'Did what',
            cell: (row) => (
                <span className="grid justify-items-start gap-1">
                    <StatusBadge tone={actions[row.action]?.tone ?? 'neutral'}>
                        {actions[row.action]?.label ?? row.action}
                    </StatusBadge>
                    <span className="text-sm text-ink">
                        {row.subject ?? row.subjectType ?? '—'}
                    </span>
                </span>
            ),
        },
        {
            key: 'account',
            header: 'Account',
            hideOnMobile: true,
            cell: (row) =>
                row.account ? (
                    <span className="block min-w-0">
                        <span className="block truncate text-ink">
                            {row.account.name}
                        </span>
                        <span className="block truncate text-xs text-ink-400">
                            {row.account.memberId}
                        </span>
                    </span>
                ) : (
                    <span className="text-ink-400">—</span>
                ),
        },
        {
            key: 'reference',
            header: 'Reference',
            hideOnMobile: true,
            className: 'font-mono text-xs text-ink-500 whitespace-nowrap',
            cell: (row) => row.reference ?? '—',
        },
        {
            key: 'details',
            header: 'Details',
            hideOnMobile: true,
            className: 'max-w-xs text-xs text-ink-500',
            cell: (row) => <Details details={row.details} />,
        },
    ];

    return (
        <>
            <Head title="Audit trail" />

            <MemberPage
                title="Audit trail"
                description="Who did what, when, on which member's account and with which reference."
            >
                <ReportToolbar
                    filters={{
                        from: filters.from ?? '',
                        to: filters.to ?? '',
                        action: filters.action,
                        type: filters.type,
                    }}
                    selects={[
                        {
                            name: 'action',
                            label: 'Action',
                            options: actionOptions,
                            allLabel: 'All actions',
                        },
                        {
                            name: 'type',
                            label: 'Record',
                            options: types,
                            allLabel: 'All records',
                        },
                    ]}
                    downloads={[{ label: 'Download' }]}
                />

                <DataTable
                    title="Activity"
                    description={`${entries.total} entries · ${todayCount} today`}
                    columns={columns}
                    page={entries}
                    getRowId={(row) => row.id}
                    searchable
                    searchPlaceholder="Search record, reference, name or IP"
                    empty={{
                        icon: History,
                        title: 'Nothing recorded',
                        description:
                            'Changes to members, money and settings appear here.',
                    }}
                />
            </MemberPage>
        </>
    );
}

AuditTrail.layout = {
    breadcrumbs: [{ title: 'Audit trail', href: auditTrail() }],
};
