import { Button } from '@/components/ui/button';
import { useTranslation } from '@/hooks/use-translation';
import { router } from '@inertiajs/react';
import { Link2, Power, Sparkles, X } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import { useCanManageYield, useReadOnlyReason } from '../hooks/useYieldPermissions';
import type { YieldTableRow } from '../types';

const NS = 'yield.index';

interface BulkActionBarProps {
    /** Currently selected rows (resolved from the selection set). */
    selectedRows: YieldTableRow[];
    onActivate: () => void;
    /** Open the "apply rule group" dialog for the selected configured rows. */
    onApplyGroup: () => void;
    onClear: () => void;
}

/**
 * Floating bottom bar shown only when rows are selected. Bulk-activate opens the
 * starting-rules dialog (handled by the parent); bulk-deactivate toggles off
 * every selected row that is currently active, accumulating per-item results
 * (same spirit as use-bulk-apply, but yield.toggle takes a config id, not the
 * uid/field/value shape that hook hardcodes for logements.bulkUpdate).
 */
export default function BulkActionBar({ selectedRows, onActivate, onApplyGroup, onClear }: BulkActionBarProps) {
    const { t } = useTranslation();
    const canManage = useCanManageYield();
    const readOnlyReason = useReadOnlyReason();
    const [running, setRunning] = useState(false);

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

    const count = selectedRows.length;
    const label = t(NS, 'bulk_selected', ':count sélectionné(s)').replace(':count', String(count));
    const hasConfigured = selectedRows.some((r) => r.has_config);

    const deactivate = () => {
        if (!canManage) return;
        const targets = selectedRows.filter((r) => r.has_config && r.is_active && r.id != null);
        if (targets.length === 0) {
            toast.error(t(NS, 'toast_error', 'Une erreur est survenue.'));
            return;
        }

        setRunning(true);
        let done = 0;
        let failed = 0;

        const next = (index: number) => {
            if (index >= targets.length) {
                setRunning(false);
                if (failed === 0) {
                    toast.success(t(NS, 'toast_deactivated', 'Yield désactivé.'));
                } else {
                    toast.warning(`${done - failed} OK, ${failed} en échec.`);
                }
                onClear();
                return;
            }
            const row = targets[index];
            router.post(
                route('yield.toggle', row.id as number),
                {},
                {
                    preserveScroll: true,
                    preserveState: true,
                    onSuccess: () => {
                        done += 1;
                        next(index + 1);
                    },
                    onError: () => {
                        done += 1;
                        failed += 1;
                        next(index + 1);
                    },
                },
            );
        };

        next(0);
    };

    return (
        <div className="bg-foreground text-background fixed bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center gap-3 rounded-full px-4 py-2 shadow-lg">
            <span className="text-sm font-medium whitespace-nowrap">{label}</span>
            <div className="flex items-center gap-1.5">
                <Button size="sm" variant="secondary" onClick={onActivate} disabled={!canManage} title={canManage ? undefined : readOnlyReason}>
                    <Sparkles className="h-3.5 w-3.5" />
                    {t(NS, 'bulk_activate', 'Activer')}
                </Button>
                <Button size="sm" variant="secondary" onClick={deactivate} disabled={running || !canManage} title={canManage ? undefined : readOnlyReason}>
                    <Power className="h-3.5 w-3.5" />
                    {t(NS, 'bulk_deactivate', 'Désactiver')}
                </Button>
                <Button
                    size="sm"
                    variant="secondary"
                    onClick={onApplyGroup}
                    disabled={!hasConfigured || !canManage}
                    title={canManage ? t(NS, 'bulk_apply_group_hint', 'Lier les logements configurés à un groupe de règles') : readOnlyReason}
                >
                    <Link2 className="h-3.5 w-3.5" />
                    {t(NS, 'bulk_apply_group', 'Groupe')}
                </Button>
                <Button size="sm" variant="ghost" onClick={onClear} className="text-background hover:text-background hover:bg-white/10">
                    <X className="h-3.5 w-3.5" />
                    {t(NS, 'bulk_clear', 'Effacer')}
                </Button>
            </div>
        </div>
    );
}
