import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Switch } from '@/components/ui/switch';
import { cn } from '@/lib/utils';
import type { RuleRow } from '@/types/automatisations';
import { Clock, Copy, Home, MoreHorizontal, Pencil, Trash2 } from 'lucide-react';
import { describeTrigger, fill, TONE_CLASSES } from './automatisations-format';
import { sourceLabel, type Translate } from './labels';

const NS = 'automatisations';

interface Props {
    rule: RuleRow;
    canManage: boolean;
    /** Première carte de la liste : elle porte les ancres de la visite guidée. */
    tourAnchors: boolean;
    locale: string;
    t: Translate;
    onEdit: (rule: RuleRow) => void;
    /** Ouvre l'éditeur en création, pré-rempli par cette règle (rien n'est enregistré). */
    onDuplicate: (rule: RuleRow) => void;
    onDelete: (rule: RuleRow) => void;
    onToggle: (rule: RuleRow, active: boolean) => void;
}

/**
 * Une règle, à balayer : nom et interrupteur, moment d'envoi en clair, mode
 * (ambre « À valider », vert « Automatique »), provenances, périmètre, et ce
 * qu'elle a produit sur 30 jours.
 */
export function RuleCard({ rule, canManage, tourAnchors, locale, t, onEdit, onDuplicate, onDelete, onToggle }: Props) {
    const readOnly = t(NS, 'read_only_hint', 'Lecture seule : il faut le droit de gérer les automatisations.');

    return (
        <Card className={cn('gap-0 py-0', !rule.isActive && 'bg-muted/30')}>
            <CardContent className="flex flex-col gap-3 p-4">
                <div className="flex items-start justify-between gap-2">
                    <div className="min-w-0">
                        <h3 className="truncate font-medium" title={rule.name}>
                            {rule.name}
                        </h3>
                        <p className="text-muted-foreground mt-0.5 flex items-center gap-1 text-sm">
                            <Clock className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
                            <span data-tour={tourAnchors ? 'automatisations-trigger' : undefined}>{describeTrigger(rule, locale)}</span>
                        </p>
                    </div>
                    <div className="flex shrink-0 items-center gap-1">
                        <label className="text-muted-foreground flex items-center gap-2 text-xs" title={canManage ? undefined : readOnly}>
                            <span className="hidden sm:inline">
                                {rule.isActive ? t(NS, 'rule_active', 'Active') : t(NS, 'rule_inactive', 'Éteinte')}
                            </span>
                            <Switch
                                checked={rule.isActive}
                                onCheckedChange={(next) => onToggle(rule, next)}
                                disabled={!canManage}
                                aria-label={
                                    rule.isActive ? t(NS, 'rule_deactivate', 'Désactiver la règle') : t(NS, 'rule_activate', 'Activer la règle')
                                }
                                data-tour={tourAnchors ? 'automatisations-switch' : undefined}
                            />
                        </label>
                        {canManage && (
                            <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                    <Button variant="ghost" size="icon" className="h-8 w-8" aria-label={t(NS, 'rule_menu', 'Actions de la règle')}>
                                        <MoreHorizontal className="h-4 w-4" />
                                    </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end">
                                    <DropdownMenuItem onSelect={() => onEdit(rule)}>
                                        <Pencil className="h-4 w-4" />
                                        {t(NS, 'edit', 'Modifier')}
                                    </DropdownMenuItem>
                                    <DropdownMenuItem onSelect={() => onDuplicate(rule)}>
                                        <Copy className="h-4 w-4" />
                                        {t(NS, 'duplicate', 'Dupliquer')}
                                    </DropdownMenuItem>
                                    <DropdownMenuItem onSelect={() => onDelete(rule)} className="text-red-600 focus:text-red-700">
                                        <Trash2 className="h-4 w-4" />
                                        {t(NS, 'delete', 'Supprimer')}
                                    </DropdownMenuItem>
                                </DropdownMenuContent>
                            </DropdownMenu>
                        )}
                    </div>
                </div>

                <div className="flex flex-wrap items-center gap-1.5">
                    <span
                        data-tour={tourAnchors ? 'automatisations-mode' : undefined}
                        className={cn(
                            'inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] font-medium',
                            rule.mode === 'auto' ? TONE_CLASSES.green : TONE_CLASSES.amber,
                        )}
                    >
                        {rule.mode === 'auto' ? t(NS, 'mode_auto', 'Automatique') : t(NS, 'mode_approval', 'À valider')}
                    </span>
                    {rule.sources.map((source) => (
                        <span key={source} className="bg-muted text-muted-foreground inline-flex items-center rounded-full px-2 py-0.5 text-[11px]">
                            {sourceLabel(source, t)}
                        </span>
                    ))}
                </div>

                <div className="text-muted-foreground flex flex-wrap items-center justify-between gap-x-3 gap-y-1 text-xs">
                    <span className="inline-flex items-center gap-1">
                        <Home className="h-3.5 w-3.5" aria-hidden="true" />
                        {rule.propertyScope === 'all'
                            ? t(NS, 'scope_all', 'Tous les logements')
                            : fill(
                                  rule.propertyIds.length > 1
                                      ? t(NS, 'scope_count_plural', ':count logements')
                                      : t(NS, 'scope_count', ':count logement'),
                                  {
                                      count: rule.propertyIds.length,
                                  },
                              )}
                    </span>
                    <span className="tabular-nums" title={t(NS, 'stats_hint', 'Sur les 30 derniers jours')}>
                        {fill(t(NS, 'stats_line', ':sent envoyés · :pending à valider · :failed échecs (30 j)'), {
                            sent: rule.stats.sent30d,
                            pending: rule.stats.pending,
                            failed: rule.stats.failed30d,
                        })}
                    </span>
                </div>
            </CardContent>
        </Card>
    );
}
