import { Transition } from '@headlessui/react';
import { Check, X } from 'lucide-react';
import React, { Fragment, ReactNode, isValidElement, cloneElement } from 'react';

interface Props {
    count: number;
    onClear: () => void;
    children: ReactNode;
}

/**
 * Çağıran sayfada button içinde direkt yazılmış metin node'larını mobilde gizler:
 *   <button><Icon /> Bilgilendir</button>
 * → mobilde: <button><Icon /> <span class="hidden sm:inline">Bilgilendir</span></button>
 * Böylece her sayfada tek tek <span> sarmalamaya gerek kalmaz.
 */
function metinleriMobildeGizle(children: ReactNode): ReactNode {
    return React.Children.map(children, (child) => {
        if (!isValidElement(child)) return child;
        const innerChildren = React.Children.map(
            (child.props as any).children,
            (bc: ReactNode, idx: number) => {
                if (typeof bc === 'string' && bc.trim() !== '') {
                    return (
                        <span key={`txt-${idx}`} className="hidden sm:inline">{bc}</span>
                    );
                }
                return bc;
            },
        );
        return cloneElement(child as any, {}, innerChildren);
    });
}

/**
 * Sticky alt bar — seçim olduğunda görünür, toplu işlem butonlarını içerir.
 */
export default function BulkActionBar({ count, onClear, children }: Props) {
    const islenmisChildren = metinleriMobildeGizle(children);
    return (
        <Transition
            as={Fragment}
            show={count > 0}
            enter="transition ease-out duration-200"
            enterFrom="opacity-0 translate-y-4"
            enterTo="opacity-100 translate-y-0"
            leave="transition ease-in duration-150"
            leaveFrom="opacity-100 translate-y-0"
            leaveTo="opacity-0 translate-y-4"
        >
            <div className="fixed bottom-4 left-1/2 z-40 -translate-x-1/2 sm:bottom-6">
                <div className="flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-2 py-1.5 shadow-2xl ring-1 ring-black/5 sm:gap-3 sm:px-3 sm:py-2">
                    <div className="flex items-center gap-1.5 rounded-lg bg-blue-50 px-2 py-1 sm:gap-2 sm:px-3 sm:py-1.5">
                        <Check className="h-4 w-4 text-blue-600" />
                        <span className="text-sm font-semibold text-blue-900">{count}<span className="hidden sm:inline"> seçili</span></span>
                    </div>
                    <div className="flex items-center gap-1.5 sm:gap-2">
                        {islenmisChildren}
                    </div>
                    <button
                        onClick={onClear}
                        className="rounded-md p-1.5 text-slate-500 hover:bg-slate-100 hover:text-slate-700"
                        title="Seçimi temizle"
                    >
                        <X className="h-4 w-4" />
                    </button>
                </div>
            </div>
        </Transition>
    );
}
