import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useTranslation } from '@/hooks/use-translation';
import { router } from '@inertiajs/react';
import { useState } from 'react';
import { toast } from 'sonner';
import { useCanManageYield } from '../hooks/useYieldPermissions';
import type { YieldRuleGroup } from '../types';

const NS = 'yield.index';

/** Sentinel for the "detach (no group)" option — Radix Select forbids empty values. */
const NONE = '__none__';

interface ApplyRuleGroupDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    groups: YieldRuleGroup[];
    /** Configured property uids the group will be (un)linked to. */
    targetUids: string[];
    /** Called after a successful apply so the parent can clear its selection. */
    onApplied?: () => void;
}

/**
 * Link (or detach) a rule group on the selected logements. Only CONFIGURED rows
 * can follow a group — the parent passes already-filtered uids. Posts to
 * yield.rule-groups.apply; a null group detaches.
 */
export default function ApplyRuleGroupDialog({ open, onOpenChange, groups, targetUids, onApplied }: ApplyRuleGroupDialogProps) {
    const { t } = useTranslation();
    const canManage = useCanManageYield();
    const [groupId, setGroupId] = useState<string>(NONE);
    const [processing, setProcessing] = useState(false);

    const submit = () => {
        // Le dialogue n'est atteignable que par un bouton déjà éteint sans
        // `yield.manage` ; ce retour ferme le chemin restant.
        if (!canManage) return;
        setProcessing(true);
        router.post(
            route('yield.rule-groups.apply'),
            {
                rule_group_id: groupId === NONE ? null : Number(groupId),
                property_uids: targetUids,
            },
            {
                preserveScroll: true,
                onSuccess: () => {
                    toast.success(groupId === NONE ? t(NS, 'toast_detached', 'Logements détachés.') : t(NS, 'toast_group_applied', 'Groupe appliqué.'));
                    onApplied?.();
                    onOpenChange(false);
                },
                onError: () => toast.error(t(NS, 'toast_error', 'Une erreur est survenue.')),
                onFinish: () => setProcessing(false),
            },
        );
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-md">
                <DialogHeader>
                    <DialogTitle>{t(NS, 'apply_group_title', 'Appliquer un groupe de règles')}</DialogTitle>
                    <DialogDescription>
                        {t(NS, 'apply_group_description', 'Le groupe pilote les saisons / last-minute / OBA qu’il contient. Les logements restent liés : modifier le groupe les met à jour automatiquement.')}
                    </DialogDescription>
                </DialogHeader>

                <div className="flex flex-col gap-2">
                    <Label className="text-xs">{t(NS, 'apply_group_label', 'Groupe')}</Label>
                    <Select value={groupId} onValueChange={setGroupId}>
                        <SelectTrigger>
                            <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value={NONE}>{t(NS, 'apply_group_none', 'Aucun (détacher)')}</SelectItem>
                            {groups.map((g) => (
                                <SelectItem key={g.id} value={String(g.id)}>
                                    {g.name}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                    {groups.length === 0 && (
                        <p className="text-muted-foreground text-xs">
                            {t(NS, 'apply_group_empty', 'Aucun groupe pour l’instant — crée-en un depuis « Groupes de règles ».')}
                        </p>
                    )}
                    <p className="text-muted-foreground text-xs">
                        {t(NS, 'apply_group_count', ':count logement(s) configuré(s) ciblé(s).').replace(':count', String(targetUids.length))}
                    </p>
                </div>

                <DialogFooter>
                    <Button variant="outline" onClick={() => onOpenChange(false)}>
                        {t(NS, 'dialog_cancel', 'Annuler')}
                    </Button>
                    <Button onClick={submit} disabled={processing || targetUids.length === 0}>
                        {t(NS, 'apply_group_submit', 'Appliquer')}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
