import type { ColumnDef } from '@tanstack/react-table';
import { useMemo } from 'react';
import { Checkbox } from '@/components/ui/checkbox';
import { SortableColumnHeader } from '@/components/ui/sortable-column-header';
import { DocumentAccountingClassificationBadge } from '@/features/documents/components/document-accounting-classification-badge';
import { DocumentAiStatusBadge } from '@/features/documents/components/document-ai-status-badge';
import { DocumentPrimaryCell } from '@/features/documents/components/document-primary-cell';
import { DocumentStatusBadgeDropdown } from '@/features/documents/components/document-status-badge-dropdown';
import { DocumentTypeLabel } from '@/features/documents/components/document-type-label';
import { DocumentRowActions } from '@/features/documents/table/document-row-actions';
import type { DocumentListItem } from '@/features/documents/types';
import { useI18n } from '@/hooks/use-i18n';

type SortHandler = (column: 'created_at' | 'accountant_status' | 'ai_status') => void;
type OpenDetailHandler = (documentId: number) => void;
type ToggleExpandHandler = (documentId: number) => void;

function formatBytes(size: number | null): string {
    if (!size || size <= 0) {
        return '-';
    }

    if (size < 1024) {
        return `${size} B`;
    }

    if (size < 1024 * 1024) {
        return `${(size / 1024).toFixed(1)} KB`;
    }

    return `${(size / (1024 * 1024)).toFixed(1)} MB`;
}

function buildDocumentsColumns(
    t: (key: string, replacements?: Record<string, string | number>) => string,
    onSort: SortHandler,
    canProcess: boolean,
    canDelete: boolean,
    canReview: boolean,
    canValidate: boolean,
    onOpenDetail: OpenDetailHandler,
    onToggleExpand: ToggleExpandHandler,
): ColumnDef<DocumentListItem>[] {
    const selectionColumn: ColumnDef<DocumentListItem> = {
        id: 'select',
        header: ({ table }) => (
            <Checkbox
                checked={
                    table.getIsAllPageRowsSelected() ||
                    (table.getIsSomePageRowsSelected() ? 'indeterminate' : false)
                }
                onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
                aria-label={t('documents.admin_index.bulk_delete.select_all_aria')}
            />
        ),
        cell: ({ row }) => (
            <Checkbox
                checked={row.getIsSelected()}
                onCheckedChange={(value) => row.toggleSelected(!!value)}
                aria-label={t('documents.admin_index.bulk_delete.select_row_aria')}
                onClick={(event) => event.stopPropagation()}
            />
        ),
        enableSorting: false,
        enableHiding: false,
    };

    return [
        ...(canDelete ? [selectionColumn] : []),
        {
            accessorKey: 'id',
            header: t('documents.admin_index.table.column_id'),
            cell: ({ row }) => (
                <span className="font-mono text-xs text-muted-foreground tabular-nums">{row.original.id}</span>
            ),
        },
        {
            id: 'document',
            header: t('documents.admin_index.table.column_document'),
            cell: ({ row }) => (
                <DocumentPrimaryCell
                    document={row.original}
                    onOpenDetail={onOpenDetail}
                    isExpanded={row.getIsExpanded()}
                    onToggleExpand={onToggleExpand}
                    alwaysAllowOpenDetail
                />
            ),
        },
        {
            id: 'type',
            header: t('documents.admin_index.table.column_type'),
            cell: ({ row }) => (
                <DocumentTypeLabel
                    typeKey={row.original.document_type.key}
                    label={row.original.document_type.label}
                />
            ),
        },
        {
            id: 'accounting_classification',
            header: t('documents.admin_index.table.column_accounting_classification'),
            cell: ({ row }) => (
                <DocumentAccountingClassificationBadge
                    classification={row.original.accounting_classification}
                    label={row.original.accounting_classification_label}
                />
            ),
        },
        {
            accessorKey: 'size',
            header: t('documents.admin_index.table.column_size'),
            cell: ({ row }) => formatBytes(row.original.size),
        },
        {
            accessorKey: 'accountant_status',
            header: () => (
                <SortableColumnHeader
                    label={t('documents.admin_index.table.column_accountant_status')}
                    onSort={() => onSort('accountant_status')}
                />
            ),
            cell: ({ row }) => (
                <DocumentStatusBadgeDropdown
                    documentId={row.original.id}
                    aiStatus={row.original.ai_status}
                    accountantStatus={row.original.accountant_status}
                    canReview={canReview}
                    canValidate={canValidate}
                />
            ),
        },
        {
            accessorKey: 'ai_status',
            header: () => (
                <SortableColumnHeader
                    label={t('documents.admin_index.table.column_ai_status')}
                    onSort={() => onSort('ai_status')}
                />
            ),
            cell: ({ row }) => <DocumentAiStatusBadge status={row.original.ai_status} />,
        },
        {
            id: 'actions',
            header: () => (
                <span className="block text-end text-[11px] font-semibold leading-tight text-foreground/85">
                    {t('documents.admin_index.table.column_actions')}
                </span>
            ),
            cell: ({ row }) => (
                <DocumentRowActions
                    documentId={row.original.id}
                    canProcess={canProcess}
                    canDelete={canDelete}
                />
            ),
        },
    ];
}

export function useDocumentsColumns(
    onSort: SortHandler,
    canProcess: boolean,
    canDelete: boolean,
    canReview: boolean,
    canValidate: boolean,
    onOpenDetail: OpenDetailHandler,
    onToggleExpand: ToggleExpandHandler,
) {
    const { t } = useI18n();

    return useMemo(
        () =>
            buildDocumentsColumns(
                t,
                onSort,
                canProcess,
                canDelete,
                canReview,
                canValidate,
                onOpenDetail,
                onToggleExpand,
            ),
        [t, onSort, canProcess, canDelete, canReview, canValidate, onOpenDetail, onToggleExpand],
    );
}
