import { Link, router } from '@inertiajs/react';
import { useState, useRef, useEffect, useMemo } from 'react';
import {
    useReactTable,
    getCoreRowModel,
    flexRender,
} from '@tanstack/react-table';
import { useToast } from './Toaster';
import { dateFirstColumns, formatDate, isDateColumnKey } from '../lib/format';

/* ─────────────────────────────────────────────────────────────
   Density presets — row padding + text size
   ───────────────────────────────────────────────────────────── */
const DENSITY = {
    compact:     { head: 'h-9  text-[0.6875rem]', cell: 'py-1.5 text-xs',  row: '' },
    normal:      { head: 'h-11 text-xs',           cell: 'py-2.5 text-sm',  row: '' },
    comfortable: { head: 'h-14 text-xs',           cell: 'py-4 text-sm',    row: '' },
};

/* ─────────────────────────────────────────────────────────────
   Sort glyph — animated, gold-accented
   ───────────────────────────────────────────────────────────── */
function SortGlyph({ state }) {
    return (
        <span className="relative inline-flex flex-col items-center justify-center w-3 h-3 ml-1.5 shrink-0">
            <svg className={`absolute w-2.5 h-2.5 -mt-[3px] transition-all ${state === 'asc' ? 'text-primary-600 scale-110' : 'text-gray-300 opacity-0 group-hover:opacity-100'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M5 15l7-7 7 7" />
            </svg>
            <svg className={`absolute w-2.5 h-2.5 mt-[3px] transition-all ${state === 'desc' ? 'text-primary-600 scale-110' : 'text-gray-300 opacity-0 group-hover:opacity-100'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
            </svg>
        </span>
    );
}

/* ─────────────────────────────────────────────────────────────
   Density toggle — segmented control
   ───────────────────────────────────────────────────────────── */
function DensityToggle({ value, onChange }) {
    const options = [
        { key: 'compact',     label: 'Compact',     icon: 'M4 6h16M4 12h16M4 18h16' },
        { key: 'normal',      label: 'Normal',      icon: 'M4 7h16M4 12h16M4 17h16' },
        { key: 'comfortable', label: 'Comfortable', icon: 'M4 6h16M4 18h16' },
    ];
    return (
        <div className="inline-flex items-center gap-0.5 p-0.5 bg-gray-100 rounded-lg border border-gray-200">
            {options.map(opt => (
                <button
                    key={opt.key}
                    type="button"
                    onClick={() => onChange(opt.key)}
                    title={opt.label}
                    className={`p-1.5 rounded-md transition-all ${value === opt.key ? 'bg-white text-primary-700 shadow-sm' : 'text-gray-400 hover:text-gray-600'}`}
                >
                    <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d={opt.icon} />
                    </svg>
                </button>
            ))}
        </div>
    );
}

/**
 * Feature-rich data table built on TanStack Table v8.
 * Backward-compatible with the previous `columns` prop shape:
 *   { key, label, render?, sortable?, align?, visible?, className?, width? }
 *
 * New capabilities:
 *   • Column resizing (drag the right edge of any header)
 *   • Density toggle (compact / normal / comfortable) — persisted in localStorage
 *   • Sticky first column when selectable
 *   • Polished hover / selected / loading states
 *   • Animated sort glyph
 */
export function Table({
    columns,
    rows,
    actions,
    emptyMessage = 'No records found.',
    emptyIcon,
    emptyAction,
    selectable = false,
    selectedIds = [],
    onSelectionChange,
    sortBy = '',
    sortDir = 'desc',
    onSort,
    loading = false,
    onRowClick,
    stickyHeader = true,
    striped = false,
    resizable = true,
    tableId = 'default',
    totals,
}) {
    const [density, setDensity] = useState(() => {
        if (typeof window === 'undefined') return 'normal';
        return localStorage.getItem(`mj.table.density.${tableId}`) || 'normal';
    });

    useEffect(() => {
        if (typeof window !== 'undefined') {
            localStorage.setItem(`mj.table.density.${tableId}`, density);
        }
    }, [density, tableId]);

    const densityCls = DENSITY[density] || DENSITY.normal;

    /* Controlled selection (stays API-compatible) */
    const allSelected = rows.length > 0 && selectedIds.length === rows.length;
    const someSelected = selectedIds.length > 0 && selectedIds.length < rows.length;
    const checkboxRef = useRef(null);

    useEffect(() => {
        if (checkboxRef.current) checkboxRef.current.indeterminate = someSelected;
    }, [someSelected]);

    const toggleAll = () => {
        onSelectionChange?.(allSelected ? [] : rows.map(r => r.id));
    };
    const toggleRow = (id) => {
        onSelectionChange?.(selectedIds.includes(id) ? selectedIds.filter(x => x !== id) : [...selectedIds, id]);
    };

    const displayColumns = useMemo(() => dateFirstColumns(columns), [columns]);

    /* Map the user-facing `columns` prop → TanStack ColumnDef[] */
    const tsColumns = useMemo(() => {
        const cols = displayColumns
            .filter(c => c.visible !== false)
            .map(col => ({
                id: col.key,
                accessorKey: col.key,
                header: col.label,
                size: col.width || 150,
                minSize: 60,
                enableResizing: resizable && col.resizable !== false,
                enableSorting: !!(col.sortable && onSort),
                cell: col.render
                    ? ({ row }) => col.render(row.original)
                    : ({ getValue }) => {
                        const v = getValue();
                        return v === null || v === undefined || v === '' ? (
                            <span className="text-gray-300">—</span>
                        ) : isDateColumnKey(col.key) ? (
                            <span className="text-gray-800 tabular-nums">{formatDate(v)}</span>
                        ) : (
                            <span className="text-gray-800">{v}</span>
                        );
                    },
                meta: { align: col.align, className: col.className, mobileHidden: col.mobileHidden },
            }));
        return cols;
    }, [displayColumns, resizable, onSort]);

    const table = useReactTable({
        data: rows,
        columns: tsColumns,
        getCoreRowModel: getCoreRowModel(),
        columnResizeMode: 'onChange',
        defaultColumn: { size: 150, minSize: 60 },
        /* Server-side sorting: we don't use TanStack's sort model */
        manualSorting: true,
    });

    const handleSort = (colId) => {
        const col = columns.find(c => c.key === colId);
        if (!col?.sortable || !onSort) return;
        const newDir = sortBy === colId && sortDir === 'asc' ? 'desc' : 'asc';
        onSort(colId, newDir);
    };

    const visibleRows = table.getRowModel().rows;
    const colCount = tsColumns.length + (actions ? 1 : 0) + (selectable ? 1 : 0);

    return (
        <div className="relative">
            {/* Toolbar: density toggle lives here. Hidden on mobile where it
                only adds clutter; the horizontal scroll hint is more useful. */}
            <div className="hidden sm:flex items-center justify-between px-5 py-3 border-b border-gray-100">
                <div className="text-xs text-gray-400 font-medium">
                    {rows.length > 0 && (
                        <>
                            {selectedIds.length > 0
                                ? <span className="text-primary-700 font-semibold">{selectedIds.length} selected</span>
                                : <span>{rows.length} row{rows.length !== 1 && 's'} shown</span>}
                        </>
                    )}
                </div>
                <DensityToggle value={density} onChange={setDensity} />
            </div>
            {/* Mobile-only hint bar */}
            <div className="sm:hidden flex items-center justify-between px-4 py-2 border-b border-gray-100 text-[11px] text-gray-400">
                {rows.length > 0 && (
                    selectedIds.length > 0
                        ? <span className="text-primary-700 font-semibold">{selectedIds.length} selected</span>
                        : <span>{rows.length} row{rows.length !== 1 && 's'}</span>
                )}
                <span className="inline-flex items-center gap-1 text-gray-400">
                    <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M14 5l7 7m0 0l-7 7m7-7H3" />
                    </svg>
                    swipe
                </span>
            </div>

            {/* Loading bar — subtle top progress instead of overlay */}
            {loading && (
                <div className="absolute top-[52px] left-0 right-0 h-[2px] overflow-hidden z-10">
                    <div className="h-full bg-gradient-to-r from-transparent via-primary-500 to-transparent animate-[mjLoader_1.4s_ease-in-out_infinite]" />
                </div>
            )}

            <div className="relative overflow-x-auto">
                <table
                    className="w-full border-separate border-spacing-0"
                    style={{ width: resizable ? table.getTotalSize() : '100%', minWidth: '100%' }}
                >
                    <thead className={`${stickyHeader ? 'sticky top-0 z-[5]' : ''}`}>
                        {table.getHeaderGroups().map(hg => (
                            <tr key={hg.id} className="bg-gray-50/80 backdrop-blur-sm">
                                {selectable && (
                                    <th className={`${densityCls.head} sticky left-0 z-10 bg-gray-50/80 backdrop-blur-sm px-4 w-12 border-b border-gray-200`}>
                                        <input
                                            ref={checkboxRef}
                                            type="checkbox"
                                            checked={allSelected}
                                            onChange={toggleAll}
                                            className="rounded border-gray-300 text-primary-500 focus:ring-primary-500 focus:ring-offset-0 h-4 w-4 cursor-pointer"
                                        />
                                    </th>
                                )}
                                {hg.headers.map(header => {
                                    const col = header.column;
                                    const align = col.columnDef.meta?.align;
                                    const mobileHidden = col.columnDef.meta?.mobileHidden;
                                    const canSort = col.getCanSort();
                                    const isSorted = sortBy === header.id;
                                    const sortState = isSorted ? sortDir : null;
                                    return (
                                        <th
                                            key={header.id}
                                            colSpan={header.colSpan}
                                            style={{ width: header.getSize() }}
                                            className={`${densityCls.head} relative px-4 font-semibold uppercase tracking-wider text-gray-500 text-left border-b border-gray-200 select-none whitespace-nowrap ${mobileHidden ? 'hidden md:table-cell' : ''}`}
                                        >
                                            <div
                                                onClick={canSort ? () => handleSort(header.id) : undefined}
                                                className={`group flex items-center ${align === 'right' ? 'justify-end' : align === 'center' ? 'justify-center' : 'justify-start'} ${canSort ? 'cursor-pointer hover:text-gray-700 transition-colors' : ''}`}
                                            >
                                                <span>{flexRender(header.column.columnDef.header, header.getContext())}</span>
                                                {canSort && <SortGlyph state={sortState} />}
                                            </div>
                                            {/* Resize handle */}
                                            {resizable && header.column.getCanResize() && (
                                                <div
                                                    onMouseDown={header.getResizeHandler()}
                                                    onTouchStart={header.getResizeHandler()}
                                                    className={`absolute top-1/2 -translate-y-1/2 right-0 h-5 w-1 cursor-col-resize rounded-full transition-colors ${header.column.getIsResizing() ? 'bg-primary-500' : 'bg-transparent hover:bg-primary-300'}`}
                                                    onClick={(e) => e.stopPropagation()}
                                                />
                                            )}
                                        </th>
                                    );
                                })}
                                {actions && (
                                    <th className={`${densityCls.head} px-4 text-right font-semibold uppercase tracking-wider text-gray-500 border-b border-gray-200 whitespace-nowrap`}>
                                        Actions
                                    </th>
                                )}
                            </tr>
                        ))}
                    </thead>
                    <tbody className={loading ? 'opacity-60 transition-opacity' : 'transition-opacity'}>
                        {visibleRows.length === 0 ? (
                            <tr>
                                <td colSpan={colCount} className="p-16 text-center">
                                    <div className="flex flex-col items-center gap-3">
                                        {emptyIcon || (
                                            <div className="w-14 h-14 rounded-full bg-gray-100 flex items-center justify-center">
                                                <svg className="w-7 h-7 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                                                    <path strokeLinecap="round" strokeLinejoin="round" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
                                                </svg>
                                            </div>
                                        )}
                                        <p className="text-gray-500 text-sm font-medium">{emptyMessage}</p>
                                        {emptyAction && (
                                            <button
                                                type="button"
                                                onClick={emptyAction.onClick}
                                                className="mt-2 inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-white bg-primary-500 hover:bg-primary-600 rounded-lg transition-colors"
                                            >
                                                <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                                                    <path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
                                                </svg>
                                                {emptyAction.label}
                                            </button>
                                        )}
                                    </div>
                                </td>
                            </tr>
                        ) : (
                            visibleRows.map((row, i) => {
                                const isSelected = selectable && selectedIds.includes(row.original.id);
                                return (
                                    <tr
                                        key={row.id}
                                        className={`
                                            group transition-colors duration-100
                                            ${isSelected ? 'bg-primary-50/60' : striped && i % 2 === 1 ? 'bg-gray-50/40' : 'bg-white'}
                                            ${onRowClick ? 'cursor-pointer' : ''}
                                            hover:bg-primary-50/40
                                        `}
                                        onClick={(e) => {
                                            if (e.target.closest('input, button, a')) return;
                                            onRowClick?.(row.original);
                                        }}
                                    >
                                        {selectable && (
                                            <td className={`${densityCls.cell} sticky left-0 z-[1] px-4 w-12 border-b border-gray-100 ${isSelected ? 'bg-primary-50/60' : 'bg-white group-hover:bg-primary-50/40'} transition-colors`}>
                                                <input
                                                    type="checkbox"
                                                    checked={isSelected}
                                                    onChange={() => toggleRow(row.original.id)}
                                                    className="rounded border-gray-300 text-primary-500 focus:ring-primary-500 focus:ring-offset-0 h-4 w-4 cursor-pointer"
                                                />
                                            </td>
                                        )}
                                        {row.getVisibleCells().map(cell => {
                                            const align = cell.column.columnDef.meta?.align;
                                            const className = cell.column.columnDef.meta?.className || '';
                                            const mobileHidden = cell.column.columnDef.meta?.mobileHidden;
                                            return (
                                                <td
                                                    key={cell.id}
                                                    style={{ width: cell.column.getSize() }}
                                                    className={`${densityCls.cell} px-4 border-b border-gray-100 whitespace-nowrap overflow-hidden text-ellipsis ${align === 'right' ? 'text-right' : align === 'center' ? 'text-center' : ''} ${mobileHidden ? 'hidden md:table-cell' : ''} ${className}`}
                                                >
                                                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                                                </td>
                                            );
                                        })}
                                        {actions && (
                                            <td className={`${densityCls.cell} px-4 text-right border-b border-gray-100 whitespace-nowrap`}>
                                                {actions(row.original)}
                                            </td>
                                        )}
                                    </tr>
                                );
                            })
                        )}
                    </tbody>
                    {totals && visibleRows.length > 0 && (
                        <tfoot className="sticky bottom-0 z-[4]">
                            <tr className="bg-primary-50/70 backdrop-blur-sm border-t-2 border-primary-300 font-semibold">
                                {selectable && <td className={`${densityCls.cell} sticky left-0 z-[1] px-4 w-12 bg-primary-50/70`} />}
                                {displayColumns.filter(c => c.visible !== false).map(col => {
                                    const val = typeof totals[col.key] === 'function'
                                        ? totals[col.key](rows)
                                        : totals[col.key];
                                    const align = col.align;
                                    return (
                                        <td
                                            key={col.key}
                                            className={`${densityCls.cell} px-4 whitespace-nowrap text-primary-900 tabular-nums ${align === 'right' ? 'text-right' : align === 'center' ? 'text-center' : ''} ${col.mobileHidden ? 'hidden md:table-cell' : ''}`}
                                        >
                                            {val ?? ''}
                                        </td>
                                    );
                                })}
                                {actions && <td className={`${densityCls.cell} px-4`} />}
                            </tr>
                        </tfoot>
                    )}
                </table>
            </div>

            {/* Keyframes */}
            <style>{`
                @keyframes mjLoader {
                    0%   { transform: translateX(-100%); }
                    100% { transform: translateX(100%); }
                }
            `}</style>
        </div>
    );
}

/**
 * Rich pagination — matches the new table aesthetic.
 */
export function Pagination({ links, meta }) {
    if (!links || links.length <= 3) return null;

    return (
        <div className="px-4 sm:px-5 py-3 sm:py-3.5 border-t border-gray-100 flex flex-col sm:flex-row items-center justify-between gap-3 bg-gradient-to-b from-white to-gray-50/30">
            <div className="text-xs text-gray-500 text-center sm:text-left">
                {meta ? (
                    <>Showing <span className="font-semibold text-gray-800">{meta.from || 0}</span>–<span className="font-semibold text-gray-800">{meta.to || 0}</span> of <span className="font-semibold text-gray-800">{(meta.total || 0).toLocaleString('en-IN')}</span> results</>
                ) : (
                    'Showing page results'
                )}
            </div>
            <div className="flex items-center gap-1 flex-wrap justify-center max-w-full">
                {links.map((link, i) => {
                    const isDisabled = !link.url;
                    return (
                        <Link
                            key={i}
                            href={link.url || '#'}
                            preserveScroll
                            preserveState
                            className={`
                                inline-flex items-center justify-center min-w-[34px] h-8 px-2.5
                                text-xs font-semibold rounded-lg border transition-all duration-150
                                ${link.active
                                    ? 'bg-gradient-to-b from-primary-500 to-primary-600 text-white border-primary-600 shadow-[0_2px_6px_-1px_rgba(212,163,26,0.4),inset_0_1px_0_rgba(255,255,255,0.3)]'
                                    : isDisabled
                                        ? 'text-gray-300 border-transparent cursor-not-allowed pointer-events-none'
                                        : 'text-gray-600 border-gray-200 bg-white hover:border-primary-300 hover:text-primary-700 hover:shadow-sm hover:-translate-y-px'
                                }
                            `}
                            dangerouslySetInnerHTML={{ __html: link.label }}
                        />
                    );
                })}
            </div>
        </div>
    );
}

/**
 * Polished row-actions dropdown. Single "Actions" trigger opens a menu
 * with a gold accent line, spring-in animation, and color-coded hover states
 * per action type. Supports built-in view/edit/delete plus arbitrary custom
 * items via the `items` prop.
 *
 * Custom item shape:
 *   { label, icon?, href?, onClick?, color?: 'primary'|'info'|'success'|'warning'|'danger', confirm?, target? }
 */
const ACTION_ICONS = {
    view: (
        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
            <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
        </svg>
    ),
    edit: (
        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
        </svg>
    ),
    delete: (
        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
        </svg>
    ),
    dots: (
        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.25}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M5 12h.01M12 12h.01M19 12h.01" />
        </svg>
    ),
};

const MENU_COLOR_CLASSES = {
    default: 'text-gray-700 hover:bg-gray-50 hover:text-gray-900 [&>svg]:text-gray-400 hover:[&>svg]:text-primary-500',
    primary: 'text-gray-700 hover:bg-gradient-to-r hover:from-primary-50 hover:to-transparent hover:text-primary-800 [&>svg]:text-gray-400 hover:[&>svg]:text-primary-600',
    info:    'text-gray-700 hover:bg-gradient-to-r hover:from-sky-50 hover:to-transparent hover:text-sky-800 [&>svg]:text-gray-400 hover:[&>svg]:text-sky-600',
    success: 'text-gray-700 hover:bg-gradient-to-r hover:from-green-50 hover:to-transparent hover:text-green-800 [&>svg]:text-gray-400 hover:[&>svg]:text-green-600',
    warning: 'text-gray-700 hover:bg-gradient-to-r hover:from-yellow-50 hover:to-transparent hover:text-yellow-800 [&>svg]:text-gray-400 hover:[&>svg]:text-yellow-600',
    danger:  'text-gray-700 hover:bg-gradient-to-r hover:from-red-50 hover:to-transparent hover:text-red-800 [&>svg]:text-gray-400 hover:[&>svg]:text-red-600',
};

function ActionMenuItem({ item, onClose }) {
    const toast = useToast();
    const colorClass = MENU_COLOR_CLASSES[item.color] || MENU_COLOR_CLASSES.default;
    const base = `group w-full flex items-center gap-2.5 px-2.5 py-2 rounded-md text-[0.8125rem] font-medium transition-all duration-150 hover:translate-x-0.5 ${colorClass}`;

    const handleClick = async (e) => {
        if (item.confirm) {
            e.preventDefault();
            onClose();
            const ok = await toast.confirm(item.confirm, {
                variant: item.color === 'danger' ? 'error' : 'warning',
                confirmLabel: item.color === 'danger' ? 'Delete' : 'Confirm',
            });
            if (!ok) return;
            item.onClick?.();
            return;
        }
        if (item.onClick) {
            e.preventDefault();
            item.onClick();
        }
        onClose();
    };

    const content = (
        <>
            {item.icon && <span className="shrink-0 transition-transform duration-200 group-hover:scale-110">{item.icon}</span>}
            <span className="flex-1 text-left">{item.label}</span>
        </>
    );

    if (item.href) {
        return (
            <Link href={item.href} target={item.target} onClick={handleClick} className={base}>
                {content}
            </Link>
        );
    }

    return (
        <button type="button" onClick={handleClick} className={base}>
            {content}
        </button>
    );
}

export function TableActions({ editUrl, deleteUrl, viewUrl, onView, onEdit, onDelete, items: extraItems = [] }) {
    const toast = useToast();

    const menuItems = [];
    if (viewUrl || onView) {
        menuItems.push({ label: 'View', icon: ACTION_ICONS.view, color: 'info', href: viewUrl, onClick: onView });
    }
    if (editUrl || onEdit) {
        menuItems.push({ label: 'Edit', icon: ACTION_ICONS.edit, color: 'primary', href: editUrl, onClick: onEdit });
    }
    menuItems.push(...extraItems);
    if (deleteUrl || onDelete) {
        menuItems.push({
            label: 'Delete',
            icon: ACTION_ICONS.delete,
            color: 'danger',
            confirm: 'Are you sure you want to delete this record?',
            onClick: () => {
                if (deleteUrl) router.delete(deleteUrl);
                else onDelete?.();
            },
        });
    }

    if (menuItems.length === 0) return null;

    const handleAction = async (item, e) => {
        e.stopPropagation();

        if (item.confirm) {
            const ok = await toast.confirm(item.confirm, {
                variant: item.color === 'danger' ? 'error' : 'warning',
                confirmLabel: item.color === 'danger' ? 'Delete' : 'Confirm',
            });
            if (!ok) return;
        }

        item.onClick?.();
    };

    const buttonClass = (item, index) => {
        const color = {
            default: 'text-gray-600 hover:text-gray-900 hover:bg-gray-50',
            primary: 'text-primary-700 hover:text-primary-900 hover:bg-primary-50',
            info: 'text-sky-700 hover:text-sky-900 hover:bg-sky-50',
            success: 'text-green-700 hover:text-green-900 hover:bg-green-50',
            warning: 'text-yellow-700 hover:text-yellow-900 hover:bg-yellow-50',
            danger: 'text-red-700 hover:text-red-900 hover:bg-red-50',
        }[item.color || 'default'];
        const radius = index === 0
            ? 'rounded-l-lg'
            : index === menuItems.length - 1
                ? 'rounded-r-lg -ml-px'
                : '-ml-px';

        return `group inline-flex h-8 items-center gap-1.5 border border-gray-200 bg-white px-2.5 text-xs font-semibold shadow-sm transition-colors ${radius} ${color}`;
    };

    return (
        <div className="inline-flex items-center justify-end whitespace-nowrap">
            {menuItems.map((item, index) => {
                const content = (
                    <>
                        {item.icon && <span className="shrink-0 [&>svg]:w-3.5 [&>svg]:h-3.5">{item.icon}</span>}
                        <span>{item.label}</span>
                    </>
                );

                if (item.href) {
                    return (
                        <Link
                            key={`${item.label}-${index}`}
                            href={item.href}
                            target={item.target}
                            onClick={(e) => {
                                if (item.onClick || item.confirm) {
                                    e.preventDefault();
                                    handleAction(item, e);
                                } else {
                                    e.stopPropagation();
                                }
                            }}
                            className={buttonClass(item, index)}
                        >
                            {content}
                        </Link>
                    );
                }

                return (
                    <button
                        key={`${item.label}-${index}`}
                        type="button"
                        onClick={(e) => handleAction(item, e)}
                        className={buttonClass(item, index)}
                    >
                        {content}
                    </button>
                );
            })}
        </div>
    );
}
