'use client';

import React, { createContext, useContext, useMemo } from 'react';
import { GripVertical } from 'lucide-react';
import type { ColumnType } from 'antd/es/table';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { isListingSkeletonRow } from '@/components/tables/listingSkeletonRows';

type SortableRowContextValue = {
    attributes: ReturnType<typeof useSortable>['attributes'];
    listeners: ReturnType<typeof useSortable>['listeners'];
};

const SortableRowContext = createContext<SortableRowContextValue | null>(null);

function ParametrosOrdemDragHandleCell() {
    const ctx = useContext(SortableRowContext);
    if (!ctx) {
        return null;
    }

    return (
        <button
            type="button"
            className="parametros-ordem-drag-handle"
            aria-label="Arrastar para reordenar"
            {...ctx.attributes}
            {...ctx.listeners}
            style={{
                cursor: 'grab',
                touchAction: 'none',
                border: 0,
                background: 'transparent',
                padding: '4px 8px',
                display: 'inline-flex',
                alignItems: 'center',
                color: 'var(--text-subtle, rgba(0,0,0,0.45))',
            }}
        >
            <GripVertical size={16} aria-hidden />
        </button>
    );
}

export function createParametrosOrdemSortableTableComponents(enabled: boolean) {
    if (!enabled) {
        return undefined;
    }

    const Row = (props: React.HTMLAttributes<HTMLTableRowElement> & { 'data-row-key'?: React.Key }) => {
        const rowKey = props['data-row-key'];
        const isSkeleton = rowKey != null && isListingSkeletonRow(rowKey);

        const sortable = useSortable({
            id: rowKey == null ? 'unknown' : typeof rowKey === 'bigint' ? String(rowKey) : rowKey,
            disabled: !enabled || isSkeleton || rowKey == null,
        });

        const style: React.CSSProperties = {
            ...props.style,
            transform: CSS.Transform.toString(sortable.transform),
            transition: sortable.transition,
            opacity: sortable.isDragging ? 0.55 : props.style?.opacity,
        };

        const rowContext = useMemo(
            () =>
                enabled && !isSkeleton
                    ? { attributes: sortable.attributes, listeners: sortable.listeners }
                    : null,
            [enabled, isSkeleton, sortable.attributes, sortable.listeners],
        );

        return (
            <SortableRowContext.Provider value={rowContext}>
                <tr {...props} ref={sortable.setNodeRef} style={style} />
            </SortableRowContext.Provider>
        );
    };

    return {
        body: {
            row: Row,
        },
    };
}

export function buildParametrosOrdemDragColumn<T>(
    enabled: boolean,
): ColumnType<T> | null {
    if (!enabled) {
        return null;
    }

    return {
        key: '__ordem_drag',
        title: '',
        width: 44,
        align: 'center',
        className: 'parametros-ordem-drag-column',
        render: () => <ParametrosOrdemDragHandleCell />,
    };
}
