/**
 * Pagina Notifiche Multi-canale – gestione canali e regole di notifica.
 *
 * Struttura:
 *  - Tab "Canali" → lista canali con tipo, stato, circuit breaker, pulsante test
 *  - Tab "Regole" → lista regole evento→canale con filtri opzionali
 *  - Tab "Log"    → log degli invii recenti
 *
 * Canali supportati: Webhook, Email SMTP, Telegram, WhatsApp.
 */

import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  Bell,
  Plus,
  Edit,
  Trash2,
  Webhook,
  Mail,
  MessageCircle,
  Phone,
  CheckCircle,
  XCircle,
  FlaskConical,
  AlertTriangle,
  Zap,
} from 'lucide-react'
import { useForm } from 'react-hook-form'
import toast from 'react-hot-toast'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Label } from '@/components/ui/Label'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/Dialog'
import { notificationsApi } from '@/api/notifications.api'
import { getErrorMessage } from '@/api/client'
import { formatDate, formatRelative } from '@/lib/utils'
import { cn } from '@/lib/utils'
import type {
  NotificationChannelCreate,
  NotificationChannelResponse,
  NotificationChannelType,
  NotificationEventType,
  NotificationRuleCreate,
  NotificationRuleResponse,
} from '@/types/api.types'

// ─── Costanti ─────────────────────────────────────────────────────────────────

const CHANNEL_TYPE_LABELS: Record<NotificationChannelType, string> = {
  webhook: 'Webhook',
  email: 'Email SMTP',
  telegram: 'Telegram',
  whatsapp: 'WhatsApp',
}

const CHANNEL_TYPE_ICONS: Record<NotificationChannelType, React.ElementType> = {
  webhook: Webhook,
  email: Mail,
  telegram: MessageCircle,
  whatsapp: Phone,
}

const CHANNEL_TYPE_COLORS: Record<NotificationChannelType, string> = {
  webhook: 'bg-purple-100 text-purple-800',
  email: 'bg-blue-100 text-blue-800',
  telegram: 'bg-sky-100 text-sky-800',
  whatsapp: 'bg-green-100 text-green-800',
}

const EVENT_TYPE_LABELS: Record<NotificationEventType, string> = {
  new_message: 'Nuovo messaggio',
  state_changed: 'Cambio stato',
  anomaly: 'Anomalia',
  send_failed: 'Invio fallito',
  send_delivered: 'Invio consegnato',
  mailbox_error: 'Errore casella',
}

const STATUS_COLORS: Record<string, string> = {
  sent: 'bg-green-100 text-green-800',
  pending: 'bg-yellow-100 text-yellow-800',
  failed: 'bg-red-100 text-red-800',
  skipped: 'bg-gray-100 text-gray-600',
}

const STATUS_LABELS: Record<string, string> = {
  sent: 'Inviato',
  pending: 'In attesa',
  failed: 'Fallito',
  skipped: 'Saltato',
}

// ─── Tab type ─────────────────────────────────────────────────────────────────

type Tab = 'channels' | 'rules' | 'logs'

// ─── Pagina principale ────────────────────────────────────────────────────────

export function NotificationsPage() {
  const [activeTab, setActiveTab] = useState<Tab>('channels')
  const [showCreateChannel, setShowCreateChannel] = useState(false)
  const [editingChannel, setEditingChannel] = useState<NotificationChannelResponse | null>(null)
  const [showCreateRule, setShowCreateRule] = useState(false)
  const queryClient = useQueryClient()

  const tabs: { id: Tab; label: string }[] = [
    { id: 'channels', label: 'Canali' },
    { id: 'rules', label: 'Regole' },
    { id: 'logs', label: 'Log invii' },
  ]

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="border-b bg-background px-6 py-4 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Bell className="h-5 w-5 text-primary" />
          <h1 className="text-xl font-semibold">Notifiche Multi-canale</h1>
        </div>
        {activeTab === 'channels' && (
          <Button onClick={() => setShowCreateChannel(true)}>
            <Plus className="h-4 w-4 mr-2" />
            Nuovo canale
          </Button>
        )}
        {activeTab === 'rules' && (
          <Button onClick={() => setShowCreateRule(true)}>
            <Plus className="h-4 w-4 mr-2" />
            Nuova regola
          </Button>
        )}
      </div>

      {/* Tab bar */}
      <div className="border-b bg-background px-6">
        <div className="flex gap-1">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={cn(
                'px-4 py-3 text-sm font-medium border-b-2 -mb-px transition-colors',
                activeTab === tab.id
                  ? 'border-primary text-primary'
                  : 'border-transparent text-muted-foreground hover:text-foreground',
              )}
            >
              {tab.label}
            </button>
          ))}
        </div>
      </div>

      {/* Contenuto */}
      <div className="flex-1 overflow-auto p-6">
        {activeTab === 'channels' && (
          <ChannelsTab
            onEdit={(c) => setEditingChannel(c)}
            onCreated={() => queryClient.invalidateQueries({ queryKey: ['notif-channels'] })}
          />
        )}
        {activeTab === 'rules' && <RulesTab />}
        {activeTab === 'logs' && <LogsTab />}
      </div>

      {/* Dialogs */}
      {(showCreateChannel || editingChannel) && (
        <ChannelFormDialog
          open
          editingChannel={editingChannel}
          onClose={() => {
            setShowCreateChannel(false)
            setEditingChannel(null)
          }}
          onSaved={() => {
            queryClient.invalidateQueries({ queryKey: ['notif-channels'] })
            setShowCreateChannel(false)
            setEditingChannel(null)
          }}
        />
      )}

      {showCreateRule && (
        <RuleFormDialog
          open
          onClose={() => setShowCreateRule(false)}
          onSaved={() => {
            queryClient.invalidateQueries({ queryKey: ['notif-rules'] })
            setShowCreateRule(false)
          }}
        />
      )}
    </div>
  )
}

// ─── Tab Canali ───────────────────────────────────────────────────────────────

interface ChannelsTabProps {
  onEdit: (c: NotificationChannelResponse) => void
  onCreated: () => void
}

function ChannelsTab({ onEdit }: ChannelsTabProps) {
  const queryClient = useQueryClient()

  const { data, isLoading } = useQuery({
    queryKey: ['notif-channels'],
    queryFn: () => notificationsApi.listChannels({ page_size: 100 }),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => notificationsApi.deleteChannel(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notif-channels'] })
      toast.success('Canale eliminato')
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const testMutation = useMutation({
    mutationFn: (id: string) => notificationsApi.testChannel(id),
    onSuccess: (result) => {
      if (result.success) {
        toast.success(` ${result.message}`)
      } else {
        toast.error(` ${result.message}`)
      }
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const toggleActiveMutation = useMutation({
    mutationFn: ({ id, active }: { id: string; active: boolean }) =>
      notificationsApi.updateChannel(id, { is_active: active }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['notif-channels'] }),
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const channels = data?.items ?? []

  if (isLoading)
    return (
      <div className="flex justify-center py-12">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    )

  if (channels.length === 0)
    return (
      <div className="flex flex-col items-center justify-center py-16 text-center">
        <Bell className="h-12 w-12 text-muted-foreground mb-4 opacity-40" />
        <p className="text-lg font-medium text-muted-foreground">Nessun canale configurato</p>
        <p className="text-sm text-muted-foreground mt-1">
          Aggiungi un canale Webhook, Email, Telegram o WhatsApp per ricevere notifiche.
        </p>
      </div>
    )

  return (
    <div className="space-y-3">
      {channels.map((channel) => {
        const Icon = CHANNEL_TYPE_ICONS[channel.channel_type as NotificationChannelType] ?? Bell
        const isCircuitOpen =
          channel.circuit_open_until && new Date(channel.circuit_open_until) > new Date()

        return (
          <div
            key={channel.id}
            className={cn(
              'rounded-lg border bg-card p-4 flex items-start gap-4',
              !channel.is_active && 'opacity-60',
            )}
          >
            {/* Icona tipo */}
            <div
              className={cn(
                'p-2.5 rounded-lg flex-shrink-0',
                CHANNEL_TYPE_COLORS[channel.channel_type as NotificationChannelType],
              )}
            >
              <Icon className="h-5 w-5" />
            </div>

            {/* Info */}
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 flex-wrap">
                <span className="font-medium">{channel.name}</span>
                <span
                  className={cn(
                    'inline-flex rounded-full px-2 py-0.5 text-xs font-medium',
                    CHANNEL_TYPE_COLORS[channel.channel_type as NotificationChannelType],
                  )}
                >
                  {CHANNEL_TYPE_LABELS[channel.channel_type as NotificationChannelType] ??
                    channel.channel_type}
                </span>
                <span
                  className={cn(
                    'inline-flex rounded-full px-2 py-0.5 text-xs font-medium',
                    channel.is_active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600',
                  )}
                >
                  {channel.is_active ? 'Attivo' : 'Inattivo'}
                </span>
              </div>

              {/* Config pubblica */}
              {channel.config && Object.keys(channel.config).length > 0 && (
                <div className="mt-1 flex gap-3 flex-wrap">
                  {Object.entries(channel.config).map(([k, v]) => (
                    <span key={k} className="text-xs text-muted-foreground">
                      <span className="font-medium">{k}:</span>{' '}
                      <span className="font-mono">{String(v)}</span>
                    </span>
                  ))}
                </div>
              )}

              {/* Circuit breaker warning */}
              {isCircuitOpen && (
                <div className="mt-1.5 flex items-center gap-1.5 text-xs text-orange-700 bg-orange-50 rounded px-2 py-1 w-fit">
                  <AlertTriangle className="h-3.5 w-3.5" />
                  Circuit breaker aperto fino a {formatDate(channel.circuit_open_until)}
                </div>
              )}

              {/* Failures */}
              {channel.consecutive_failures > 0 && (
                <p className="text-xs text-red-600 mt-1">
                  {channel.consecutive_failures} errori consecutivi
                </p>
              )}
            </div>

            {/* Azioni */}
            <div className="flex items-center gap-1 shrink-0">
              <Button
                variant="outline"
                size="sm"
                onClick={() => testMutation.mutate(channel.id)}
                isLoading={testMutation.isPending}
                title="Testa canale"
              >
                <FlaskConical className="h-3.5 w-3.5 mr-1" />
                Test
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8"
                title="Modifica"
                onClick={() => onEdit(channel)}
              >
                <Edit className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8"
                title={channel.is_active ? 'Disattiva' : 'Attiva'}
                onClick={() =>
                  toggleActiveMutation.mutate({ id: channel.id, active: !channel.is_active })
                }
              >
                {channel.is_active ? (
                  <XCircle className="h-4 w-4 text-yellow-500" />
                ) : (
                  <CheckCircle className="h-4 w-4 text-green-500" />
                )}
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8"
                title="Elimina"
                onClick={() => {
                  if (confirm(`Eliminare il canale "${channel.name}"?`)) {
                    deleteMutation.mutate(channel.id)
                  }
                }}
              >
                <Trash2 className="h-4 w-4 text-red-500" />
              </Button>
            </div>
          </div>
        )
      })}
    </div>
  )
}

// ─── Tab Regole ───────────────────────────────────────────────────────────────

function RulesTab() {
  const queryClient = useQueryClient()

  const { data: channelsData } = useQuery({
    queryKey: ['notif-channels'],
    queryFn: () => notificationsApi.listChannels({ page_size: 100 }),
  })

  const { data, isLoading } = useQuery({
    queryKey: ['notif-rules'],
    queryFn: () => notificationsApi.listRules({ page_size: 100 }),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => notificationsApi.deleteRule(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notif-rules'] })
      toast.success('Regola eliminata')
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const toggleActiveMutation = useMutation({
    mutationFn: ({ id, active }: { id: string; active: boolean }) =>
      notificationsApi.updateRule(id, { is_active: active }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['notif-rules'] }),
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const channels = channelsData?.items ?? []
  const rules = data?.items ?? []

  const channelName = (id: string) =>
    channels.find((c) => c.id === id)?.name ?? id.slice(0, 8) + '…'

  if (isLoading)
    return (
      <div className="flex justify-center py-12">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    )

  if (rules.length === 0)
    return (
      <div className="flex flex-col items-center justify-center py-16 text-center">
        <Zap className="h-12 w-12 text-muted-foreground mb-4 opacity-40" />
        <p className="text-lg font-medium text-muted-foreground">Nessuna regola</p>
        <p className="text-sm text-muted-foreground mt-1">
          Le regole collegano gli eventi PEChub ai canali di notifica.
        </p>
      </div>
    )

  return (
    <div className="rounded-lg border overflow-hidden">
      <table className="w-full text-sm">
        <thead>
          <tr className="bg-muted/50 border-b">
            <th className="text-left px-4 py-3 font-medium text-muted-foreground">Regola</th>
            <th className="text-left px-4 py-3 font-medium text-muted-foreground">Evento</th>
            <th className="text-left px-4 py-3 font-medium text-muted-foreground">Canale</th>
            <th className="text-left px-4 py-3 font-medium text-muted-foreground">Stato</th>
            <th className="text-right px-4 py-3 font-medium text-muted-foreground">Azioni</th>
          </tr>
        </thead>
        <tbody className="divide-y">
          {rules.map((rule) => (
            <tr
              key={rule.id}
              className={cn('hover:bg-muted/30 transition-colors', !rule.is_active && 'opacity-60')}
            >
              <td className="px-4 py-3 font-medium">{rule.name}</td>
              <td className="px-4 py-3">
                <span className="inline-flex items-center gap-1 rounded-full bg-violet-100 text-violet-800 px-2 py-0.5 text-xs font-medium">
                  <Zap className="h-3 w-3" />
                  {EVENT_TYPE_LABELS[rule.event_type as NotificationEventType] ?? rule.event_type}
                </span>
              </td>
              <td className="px-4 py-3 text-muted-foreground">{channelName(rule.channel_id)}</td>
              <td className="px-4 py-3">
                <span
                  className={cn(
                    'inline-flex rounded-full px-2 py-0.5 text-xs font-medium',
                    rule.is_active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600',
                  )}
                >
                  {rule.is_active ? 'Attiva' : 'Inattiva'}
                </span>
              </td>
              <td className="px-4 py-3">
                <div className="flex items-center justify-end gap-1">
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8"
                    title={rule.is_active ? 'Disattiva' : 'Attiva'}
                    onClick={() =>
                      toggleActiveMutation.mutate({ id: rule.id, active: !rule.is_active })
                    }
                  >
                    {rule.is_active ? (
                      <XCircle className="h-4 w-4 text-yellow-500" />
                    ) : (
                      <CheckCircle className="h-4 w-4 text-green-500" />
                    )}
                  </Button>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8"
                    title="Elimina"
                    onClick={() => {
                      if (confirm(`Eliminare la regola "${rule.name}"?`)) {
                        deleteMutation.mutate(rule.id)
                      }
                    }}
                  >
                    <Trash2 className="h-4 w-4 text-red-500" />
                  </Button>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

// ─── Tab Log ──────────────────────────────────────────────────────────────────

function LogsTab() {
  const { data: channelsData } = useQuery({
    queryKey: ['notif-channels'],
    queryFn: () => notificationsApi.listChannels({ page_size: 100 }),
  })

  const { data, isLoading } = useQuery({
    queryKey: ['notif-logs'],
    queryFn: () => notificationsApi.listLogs({ page_size: 50 }),
  })

  const channels = channelsData?.items ?? []
  const logs = data?.items ?? []

  const channelName = (id: string) =>
    channels.find((c) => c.id === id)?.name ?? id.slice(0, 8) + '…'

  if (isLoading)
    return (
      <div className="flex justify-center py-12">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    )

  if (logs.length === 0)
    return (
      <div className="flex flex-col items-center justify-center py-16 text-center">
        <Bell className="h-12 w-12 text-muted-foreground mb-4 opacity-40" />
        <p className="text-lg font-medium text-muted-foreground">Nessun log</p>
        <p className="text-sm text-muted-foreground mt-1">
          I log appariranno qui quando verranno inviate notifiche.
        </p>
      </div>
    )

  return (
    <div className="rounded-lg border overflow-hidden">
      <table className="w-full text-sm">
        <thead>
          <tr className="bg-muted/50 border-b">
            <th className="text-left px-4 py-3 font-medium text-muted-foreground">Canale</th>
            <th className="text-left px-4 py-3 font-medium text-muted-foreground">Evento</th>
            <th className="text-left px-4 py-3 font-medium text-muted-foreground">Stato</th>
            <th className="text-left px-4 py-3 font-medium text-muted-foreground">Tentativi</th>
            <th className="text-left px-4 py-3 font-medium text-muted-foreground">Data</th>
            <th className="text-left px-4 py-3 font-medium text-muted-foreground">Errore</th>
          </tr>
        </thead>
        <tbody className="divide-y">
          {logs.map((log) => (
            <tr key={log.id} className="hover:bg-muted/30 transition-colors">
              <td className="px-4 py-3 font-medium">{channelName(log.channel_id)}</td>
              <td className="px-4 py-3 text-muted-foreground">
                {EVENT_TYPE_LABELS[log.event_type as NotificationEventType] ?? log.event_type}
              </td>
              <td className="px-4 py-3">
                <span
                  className={cn(
                    'inline-flex rounded-full px-2 py-0.5 text-xs font-medium',
                    STATUS_COLORS[log.status] ?? 'bg-gray-100 text-gray-600',
                  )}
                >
                  {STATUS_LABELS[log.status] ?? log.status}
                </span>
              </td>
              <td className="px-4 py-3 text-muted-foreground">
                {log.attempt_count}/{log.max_attempts}
              </td>
              <td className="px-4 py-3 text-xs text-muted-foreground">
                {formatRelative(log.created_at)}
              </td>
              <td className="px-4 py-3 text-xs text-red-600 max-w-xs truncate">
                {log.last_error || '—'}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

// ─── Dialog Canale ────────────────────────────────────────────────────────────

interface ChannelFormDialogProps {
  open: boolean
  editingChannel: NotificationChannelResponse | null
  onClose: () => void
  onSaved: () => void
}

interface ChannelFormValues {
  name: string
  channel_type: NotificationChannelType
  // Webhook
  webhook_url: string
  webhook_secret: string
  // Email
  email_host: string
  email_port: string
  email_user: string
  email_password: string
  email_from: string
  email_to: string
  // Telegram
  telegram_bot_token: string
  telegram_chat_id: string
  // WhatsApp
  whatsapp_phone_number_id: string
  whatsapp_access_token: string
  whatsapp_to_number: string
}

function ChannelFormDialog({ open, editingChannel, onClose, onSaved }: ChannelFormDialogProps) {
  const { register, watch, handleSubmit, formState: { errors } } = useForm<ChannelFormValues>({
    defaultValues: {
      name: editingChannel?.name ?? '',
      channel_type: (editingChannel?.channel_type as NotificationChannelType) ?? 'webhook',
      webhook_url: (editingChannel?.config?.url as string) ?? '',
      email_host: (editingChannel?.config?.host as string) ?? '',
      email_port: (editingChannel?.config?.port as string) ?? '465',
      email_from: (editingChannel?.config?.from_email as string) ?? '',
      email_to: (editingChannel?.config?.to_email as string) ?? '',
      telegram_chat_id: (editingChannel?.config?.chat_id as string) ?? '',
      whatsapp_phone_number_id: (editingChannel?.config?.phone_number_id as string) ?? '',
      whatsapp_to_number: (editingChannel?.config?.to_number as string) ?? '',
    },
  })

  const channelType = watch('channel_type')

  const createMutation = useMutation({
    mutationFn: (data: NotificationChannelCreate) => notificationsApi.createChannel(data),
    onSuccess: () => { toast.success('Canale creato'); onSaved() },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) =>
      notificationsApi.updateChannel(id, data),
    onSuccess: () => { toast.success('Canale aggiornato'); onSaved() },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const onSubmit = (values: ChannelFormValues) => {
    let config: Record<string, unknown> = {}
    let config_secret: Record<string, unknown> | null = null

    if (values.channel_type === 'webhook') {
      config = { url: values.webhook_url }
      if (values.webhook_secret) config_secret = { secret: values.webhook_secret }
    } else if (values.channel_type === 'email') {
      config = {
        host: values.email_host,
        port: parseInt(values.email_port),
        from_email: values.email_from,
        to_email: values.email_to,
      }
      if (values.email_user) config_secret = { username: values.email_user, password: values.email_password }
    } else if (values.channel_type === 'telegram') {
      config = { chat_id: values.telegram_chat_id }
      if (values.telegram_bot_token) config_secret = { bot_token: values.telegram_bot_token }
    } else if (values.channel_type === 'whatsapp') {
      config = {
        phone_number_id: values.whatsapp_phone_number_id,
        to_number: values.whatsapp_to_number,
      }
      if (values.whatsapp_access_token) config_secret = { access_token: values.whatsapp_access_token }
    }

    if (editingChannel) {
      updateMutation.mutate({
        id: editingChannel.id,
        data: { name: values.name, config, config_secret },
      })
    } else {
      createMutation.mutate({
        name: values.name,
        channel_type: values.channel_type,
        config,
        config_secret,
      })
    }
  }

  const isPending = createMutation.isPending || updateMutation.isPending

  return (
    <Dialog open={open} onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>
            {editingChannel ? 'Modifica canale' : 'Nuovo canale di notifica'}
          </DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 mt-4">
          <div className="space-y-2">
            <Label>Nome *</Label>
            <Input {...register('name', { required: 'Obbligatorio' })} placeholder="es. Webhook produzione" />
            {errors.name && <p className="text-xs text-destructive">{errors.name.message}</p>}
          </div>

          {!editingChannel && (
            <div className="space-y-2">
              <Label>Tipo canale *</Label>
              <select
                className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
                {...register('channel_type')}
              >
                {(Object.entries(CHANNEL_TYPE_LABELS) as [NotificationChannelType, string][]).map(
                  ([val, lbl]) => (
                    <option key={val} value={val}>{lbl}</option>
                  ),
                )}
              </select>
            </div>
          )}

          {/* Config per tipo */}
          {channelType === 'webhook' && (
            <>
              <div className="space-y-2">
                <Label>URL Webhook *</Label>
                <Input
                  {...register('webhook_url', { required: 'Obbligatorio' })}
                  placeholder="https://example.com/webhook"
                />
              </div>
              <div className="space-y-2">
                <Label>Segreto HMAC (opzionale)</Label>
                <Input
                  {...register('webhook_secret')}
                  type="password"
                  placeholder="Secret per firma HMAC-SHA256"
                />
              </div>
            </>
          )}

          {channelType === 'email' && (
            <>
              <div className="grid grid-cols-3 gap-2">
                <div className="col-span-2 space-y-2">
                  <Label>Host SMTP *</Label>
                  <Input {...register('email_host', { required: true })} placeholder="smtp.example.com" />
                </div>
                <div className="space-y-2">
                  <Label>Porta</Label>
                  <Input {...register('email_port')} placeholder="465" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-2">
                <div className="space-y-2">
                  <Label>Username SMTP</Label>
                  <Input {...register('email_user')} />
                </div>
                <div className="space-y-2">
                  <Label>Password SMTP</Label>
                  <Input {...register('email_password')} type="password" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-2">
                <div className="space-y-2">
                  <Label>Da *</Label>
                  <Input {...register('email_from', { required: true })} placeholder="noreply@..." />
                </div>
                <div className="space-y-2">
                  <Label>A *</Label>
                  <Input {...register('email_to', { required: true })} placeholder="destinatario@..." />
                </div>
              </div>
            </>
          )}

          {channelType === 'telegram' && (
            <>
              <div className="space-y-2">
                <Label>Bot Token *</Label>
                <Input
                  {...register('telegram_bot_token', { required: true })}
                  type="password"
                  placeholder="123456:ABC-DEF…"
                />
              </div>
              <div className="space-y-2">
                <Label>Chat ID *</Label>
                <Input
                  {...register('telegram_chat_id', { required: true })}
                  placeholder="-100123456789"
                />
              </div>
            </>
          )}

          {channelType === 'whatsapp' && (
            <>
              <div className="space-y-2">
                <Label>Phone Number ID *</Label>
                <Input {...register('whatsapp_phone_number_id', { required: true })} />
              </div>
              <div className="space-y-2">
                <Label>Access Token *</Label>
                <Input {...register('whatsapp_access_token', { required: true })} type="password" />
              </div>
              <div className="space-y-2">
                <Label>Numero destinatario *</Label>
                <Input
                  {...register('whatsapp_to_number', { required: true })}
                  placeholder="+39..."
                />
              </div>
            </>
          )}

          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose}>Annulla</Button>
            <Button type="submit" isLoading={isPending}>
              {editingChannel ? 'Salva' : 'Crea canale'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}

// ─── Dialog Regola ────────────────────────────────────────────────────────────

interface RuleFormDialogProps {
  open: boolean
  onClose: () => void
  onSaved: () => void
}

interface RuleFormValues {
  name: string
  channel_id: string
  event_type: NotificationEventType
}

function RuleFormDialog({ open, onClose, onSaved }: RuleFormDialogProps) {
  const { register, handleSubmit, formState: { errors } } = useForm<RuleFormValues>({
    defaultValues: { name: '', channel_id: '', event_type: 'new_message' },
  })

  const { data: channelsData } = useQuery({
    queryKey: ['notif-channels'],
    queryFn: () => notificationsApi.listChannels({ page_size: 100 }),
  })

  const createMutation = useMutation({
    mutationFn: (data: NotificationRuleCreate) => notificationsApi.createRule(data),
    onSuccess: () => { toast.success('Regola creata'); onSaved() },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const channels = channelsData?.items ?? []

  const onSubmit = (values: RuleFormValues) => {
    createMutation.mutate({
      name: values.name,
      channel_id: values.channel_id,
      event_type: values.event_type,
    })
  }

  return (
    <Dialog open={open} onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Nuova regola di notifica</DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 mt-4">
          <div className="space-y-2">
            <Label>Nome regola *</Label>
            <Input {...register('name', { required: 'Obbligatorio' })} placeholder="es. Avviso nuovo messaggio" />
            {errors.name && <p className="text-xs text-destructive">{errors.name.message}</p>}
          </div>

          <div className="space-y-2">
            <Label>Canale *</Label>
            <select
              className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
              {...register('channel_id', { required: 'Obbligatorio' })}
            >
              <option value="">Seleziona canale…</option>
              {channels.map((c) => (
                <option key={c.id} value={c.id}>
                  {CHANNEL_TYPE_LABELS[c.channel_type as NotificationChannelType]} – {c.name}
                </option>
              ))}
            </select>
            {errors.channel_id && (
              <p className="text-xs text-destructive">{errors.channel_id.message}</p>
            )}
          </div>

          <div className="space-y-2">
            <Label>Evento *</Label>
            <select
              className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
              {...register('event_type', { required: true })}
            >
              {(Object.entries(EVENT_TYPE_LABELS) as [NotificationEventType, string][]).map(
                ([val, lbl]) => (
                  <option key={val} value={val}>{lbl}</option>
                ),
              )}
            </select>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose}>Annulla</Button>
            <Button type="submit" isLoading={createMutation.isPending}>Crea regola</Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
