/**
 * Pagina Virtual Box – gestione filtri nominati assegnabili agli utenti.
 *
 * Struttura:
 *  - Tabella delle VBox con nome, label, n° regole, n° utenti, stato, caselle PEC
 *  - Dialog creazione/modifica con builder di regole e selezione caselle reali
 *  - Dialog assegnazione utenti
 */

import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  Filter,
  Inbox,
  Plus,
  Edit,
  Trash2,
  Users,
  ChevronDown,
  ChevronUp,
  CheckCircle,
  XCircle,
  Tag,
} from 'lucide-react'
import { useForm, useFieldArray } 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 { virtualBoxesApi } from '@/api/virtual_boxes.api'
import { mailboxesApi } from '@/api/mailboxes.api'
import { usersApi } from '@/api/users.api'
import { getErrorMessage } from '@/api/client'
import { formatDate } from '@/lib/utils'
import { cn } from '@/lib/utils'
import type {
  AssignedUserResponse,
  VirtualBoxCreate,
  VirtualBoxResponse,
  VirtualBoxRuleCreate,
  VBoxField,
  VBoxOperator,
} from '@/types/api.types'

// ─── Label/costanti ───────────────────────────────────────────────────────────

const FIELD_LABELS: Record<VBoxField, string> = {
  mailbox_id: 'Casella PEC (ID)',
  imap_folder: 'Cartella IMAP',
  subject: 'Oggetto',
  from_address: 'Mittente',
  to_address: 'Destinatario',
}

const OPERATOR_LABELS: Record<VBoxOperator, string> = {
  contains: 'contiene',
  equals: 'uguale a',
  starts_with: 'inizia per',
  ends_with: 'finisce per',
  regex: 'regex',
}

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

export function VirtualBoxesPage() {
  const queryClient = useQueryClient()
  const [showCreate, setShowCreate] = useState(false)
  const [editingVbox, setEditingVbox] = useState<VirtualBoxResponse | null>(null)
  const [assigningVbox, setAssigningVbox] = useState<VirtualBoxResponse | null>(null)
  const [expandedRules, setExpandedRules] = useState<Set<string>>(new Set())

  const { data, isLoading } = useQuery({
    queryKey: ['virtual-boxes'],
    queryFn: () => virtualBoxesApi.list({ page_size: 100 }),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => virtualBoxesApi.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['virtual-boxes'] })
      toast.success('Virtual Box eliminata')
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const toggleActive = useMutation({
    mutationFn: ({ id, active }: { id: string; active: boolean }) =>
      virtualBoxesApi.update(id, { is_active: active }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['virtual-boxes'] })
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const vboxes = data?.items ?? []

  const toggleRules = (id: string) => {
    setExpandedRules((prev) => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  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">
          <Filter className="h-5 w-5 text-primary" />
          <h1 className="text-xl font-semibold">Virtual Box</h1>
          <span className="text-sm text-muted-foreground">
            ({vboxes.filter((v) => v.is_active).length} attive su {vboxes.length})
          </span>
        </div>
        <Button onClick={() => setShowCreate(true)}>
          <Plus className="h-4 w-4 mr-2" />
          Nuova Virtual Box
        </Button>
      </div>

      {/* Descrizione */}
      <div className="px-6 py-3 bg-blue-50 border-b text-sm text-blue-800">
        <strong>Cos'è una Virtual Box?</strong> Un filtro nominato (oggetto, mittente, cartella,
        data…) assegnabile a uno o più utenti e collegato a una o più{' '}
        <strong>caselle PEC reali</strong>. Le regole nella stessa VBox si combinano in{' '}
        <strong>AND</strong>; più VBox assegnate allo stesso utente si uniscono in{' '}
        <strong>OR</strong>. Il filtro si applica automaticamente a inbox e ricerca.
      </div>

      {/* Contenuto */}
      <div className="flex-1 overflow-auto p-6">
        {isLoading ? (
          <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>
        ) : vboxes.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 text-center">
            <Filter className="h-12 w-12 text-muted-foreground mb-4 opacity-40" />
            <p className="text-lg font-medium text-muted-foreground">Nessuna Virtual Box</p>
            <p className="text-sm text-muted-foreground mt-1">
              Crea la prima Virtual Box per filtrare i messaggi visibili agli utenti.
            </p>
            <Button className="mt-4" onClick={() => setShowCreate(true)}>
              <Plus className="h-4 w-4 mr-2" />
              Crea Virtual Box
            </Button>
          </div>
        ) : (
          <div className="space-y-3">
            {vboxes.map((vbox) => (
              <VBoxCard
                key={vbox.id}
                vbox={vbox}
                rulesExpanded={expandedRules.has(vbox.id)}
                onToggleRules={() => toggleRules(vbox.id)}
                onEdit={() => setEditingVbox(vbox)}
                onAssign={() => setAssigningVbox(vbox)}
                onDelete={() => {
                  if (confirm(`Eliminare la Virtual Box "${vbox.name}"?`)) {
                    deleteMutation.mutate(vbox.id)
                  }
                }}
                onToggleActive={() =>
                  toggleActive.mutate({ id: vbox.id, active: !vbox.is_active })
                }
              />
            ))}
          </div>
        )}
      </div>

      {/* Dialogs */}
      {(showCreate || editingVbox) && (
        <VBoxFormDialog
          open
          editingVbox={editingVbox}
          onClose={() => {
            setShowCreate(false)
            setEditingVbox(null)
          }}
          onSaved={() => {
            queryClient.invalidateQueries({ queryKey: ['virtual-boxes'] })
            setShowCreate(false)
            setEditingVbox(null)
          }}
        />
      )}

      {assigningVbox && (
        <AssignUsersDialog
          vbox={assigningVbox}
          onClose={() => setAssigningVbox(null)}
          onSaved={() => {
            queryClient.invalidateQueries({ queryKey: ['virtual-boxes'] })
            setAssigningVbox(null)
          }}
        />
      )}
    </div>
  )
}

// ─── Card singola VBox ────────────────────────────────────────────────────────

interface VBoxCardProps {
  vbox: VirtualBoxResponse
  rulesExpanded: boolean
  onToggleRules: () => void
  onEdit: () => void
  onAssign: () => void
  onDelete: () => void
  onToggleActive: () => void
}

function VBoxCard({
  vbox,
  rulesExpanded,
  onToggleRules,
  onEdit,
  onAssign,
  onDelete,
  onToggleActive,
}: VBoxCardProps) {
  return (
    <div
      className={cn(
        'rounded-lg border bg-card transition-colors',
        !vbox.is_active && 'opacity-60',
      )}
    >
      {/* Intestazione */}
      <div className="flex items-center gap-3 px-4 py-3">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <span className="font-medium">{vbox.name}</span>
            {vbox.label && (
              <span className="inline-flex items-center gap-1 rounded-full bg-blue-100 text-blue-800 px-2 py-0.5 text-xs">
                <Tag className="h-3 w-3" />
                {vbox.label}
              </span>
            )}
            <span
              className={cn(
                'inline-flex rounded-full px-2 py-0.5 text-xs font-medium',
                vbox.is_active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600',
              )}
            >
              {vbox.is_active ? 'Attiva' : 'Inattiva'}
            </span>
          </div>
          {vbox.description && (
            <p className="text-xs text-muted-foreground mt-0.5">{vbox.description}</p>
          )}

          {/* Caselle PEC associate */}
          {vbox.mailboxes.length > 0 ? (
            <div className="flex flex-wrap gap-1 mt-1.5">
              {vbox.mailboxes.map((mb) => (
                <span
                  key={mb.id}
                  className="inline-flex items-center gap-1 rounded-full bg-indigo-100 text-indigo-800 px-2 py-0.5 text-xs"
                >
                  <Inbox className="h-3 w-3" />
                  {mb.display_name ?? mb.email_address}
                </span>
              ))}
            </div>
          ) : (
            <p className="text-xs text-amber-600 mt-1">
              Nessuna casella PEC associata
            </p>
          )}
        </div>

        {/* Stats */}
        <div className="flex items-center gap-4 text-xs text-muted-foreground shrink-0">
          <span className="flex items-center gap-1">
            <Filter className="h-3.5 w-3.5" />
            {vbox.rules.length} {vbox.rules.length === 1 ? 'regola' : 'regole'}
          </span>
          <span className="flex items-center gap-1">
            <Users className="h-3.5 w-3.5" />
            {vbox.assignment_count} {vbox.assignment_count === 1 ? 'utente' : 'utenti'}
          </span>
          <span>{formatDate(vbox.updated_at)}</span>
        </div>

        {/* Azioni */}
        <div className="flex items-center gap-1 shrink-0">
          <Button variant="ghost" size="icon" className="h-8 w-8" title="Assegna utenti" onClick={onAssign}>
            <Users className="h-4 w-4" />
          </Button>
          <Button variant="ghost" size="icon" className="h-8 w-8" title="Modifica" onClick={onEdit}>
            <Edit className="h-4 w-4" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8"
            title={vbox.is_active ? 'Disattiva' : 'Attiva'}
            onClick={onToggleActive}
          >
            {vbox.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={onDelete}
          >
            <Trash2 className="h-4 w-4 text-red-500" />
          </Button>
          {vbox.rules.length > 0 && (
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8"
              title={rulesExpanded ? 'Nascondi regole' : 'Mostra regole'}
              onClick={onToggleRules}
            >
              {rulesExpanded ? (
                <ChevronUp className="h-4 w-4" />
              ) : (
                <ChevronDown className="h-4 w-4" />
              )}
            </Button>
          )}
        </div>
      </div>

      {/* Regole espanse */}
      {rulesExpanded && vbox.rules.length > 0 && (
        <div className="border-t px-4 py-3">
          <p className="text-xs font-medium text-muted-foreground mb-2 uppercase tracking-wide">
            Regole (combinate in AND)
          </p>
          <div className="space-y-1.5">
            {vbox.rules.map((rule, i) => (
              <div
                key={rule.id}
                className="flex items-center gap-2 text-sm bg-muted/40 rounded px-3 py-1.5"
              >
                <span className="text-xs text-muted-foreground w-4">{i + 1}.</span>
                <span className="font-medium">{FIELD_LABELS[rule.field as VBoxField] ?? rule.field}</span>
                <span className="text-muted-foreground">
                  {OPERATOR_LABELS[rule.operator as VBoxOperator] ?? rule.operator}
                </span>
                <span className="font-mono bg-background rounded px-1.5 py-0.5 text-xs border">
                  {rule.value}
                </span>
                {(rule.date_from || rule.date_to) && (
                  <span className="text-muted-foreground text-xs ml-2">
                    {rule.date_from && `dal ${rule.date_from}`}
                    {rule.date_from && rule.date_to && ' '}
                    {rule.date_to && `al ${rule.date_to}`}
                  </span>
                )}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}

// ─── Dialog crea/modifica VBox ────────────────────────────────────────────────

interface VBoxFormValues {
  name: string
  description: string
  label: string
  mailbox_ids: string[]
  rules: Array<{
    field: VBoxField
    operator: VBoxOperator
    value: string
    date_from: string
    date_to: string
  }>
}

interface VBoxFormDialogProps {
  open: boolean
  editingVbox: VirtualBoxResponse | null
  onClose: () => void
  onSaved: () => void
}

function VBoxFormDialog({ open, editingVbox, onClose, onSaved }: VBoxFormDialogProps) {
  const { register, control, handleSubmit, watch, setValue, formState: { errors } } =
    useForm<VBoxFormValues>({
      defaultValues: editingVbox
        ? {
            name: editingVbox.name,
            description: editingVbox.description ?? '',
            label: editingVbox.label ?? '',
            mailbox_ids: editingVbox.mailboxes.map((m) => m.id),
            rules: editingVbox.rules.map((r) => ({
              field: r.field as VBoxField,
              operator: r.operator as VBoxOperator,
              value: r.value,
              date_from: r.date_from ?? '',
              date_to: r.date_to ?? '',
            })),
          }
        : {
            name: '',
            description: '',
            label: '',
            mailbox_ids: [],
            rules: [],
          },
    })

  const { fields, append, remove } = useFieldArray({ control, name: 'rules' })
  const selectedMailboxIds = watch('mailbox_ids')

  // Carica le mailbox disponibili
  const { data: mailboxesData } = useQuery({
    queryKey: ['mailboxes-brief'],
    queryFn: () => mailboxesApi.list(1, 100),
  })
  const availableMailboxes = mailboxesData?.items ?? []

  const toggleMailbox = (id: string) => {
    const current = selectedMailboxIds ?? []
    if (current.includes(id)) {
      setValue('mailbox_ids', current.filter((x) => x !== id))
    } else {
      setValue('mailbox_ids', [...current, id])
    }
  }

  const createMutation = useMutation({
    mutationFn: (data: VirtualBoxCreate) => virtualBoxesApi.create(data),
    onSuccess: () => { toast.success('Virtual Box creata'); onSaved() },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const updateMutation = useMutation({
    mutationFn: ({ id, rules }: { id: string; rules: VirtualBoxRuleCreate[] }) =>
      virtualBoxesApi.replaceRules(id, rules),
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const updateMetaMutation = useMutation({
    mutationFn: ({ id, data, rules }: { id: string; data: any; rules: VirtualBoxRuleCreate[] }) =>
      virtualBoxesApi.update(id, data),
    onSuccess: async (_, vars) => {
      await updateMutation.mutateAsync({ id: vars.id, rules: vars.rules })
      toast.success('Virtual Box aggiornata')
      onSaved()
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const onSubmit = (data: VBoxFormValues) => {
    const rules: VirtualBoxRuleCreate[] = data.rules.map((r) => ({
      field: r.field,
      operator: r.operator,
      value: r.value,
      date_from: r.date_from || null,
      date_to: r.date_to || null,
    }))

    if (editingVbox) {
      updateMetaMutation.mutate({
        id: editingVbox.id,
        data: {
          name: data.name,
          description: data.description || null,
          label: data.label || null,
          mailbox_ids: data.mailbox_ids,
        },
        rules,
      })
    } else {
      createMutation.mutate({
        name: data.name,
        description: data.description || null,
        label: data.label || null,
        rules,
        mailbox_ids: data.mailbox_ids,
      })
    }
  }

  const isPending = createMutation.isPending || updateMetaMutation.isPending

  return (
    <Dialog open={open} onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>
            {editingVbox ? 'Modifica Virtual Box' : 'Nuova Virtual Box'}
          </DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-5 mt-4">
          {/* Metadati */}
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2 col-span-2">
              <Label>Nome *</Label>
              <Input
                {...register('name', { required: 'Obbligatorio' })}
                placeholder="es. Multe da info@comune.it"
              />
              {errors.name && <p className="text-xs text-destructive">{errors.name.message}</p>}
            </div>
            <div className="space-y-2">
              <Label>Etichetta</Label>
              <Input
                {...register('label')}
                placeholder="es. Comune, Fornitori…"
              />
            </div>
            <div className="space-y-2">
              <Label>Descrizione</Label>
              <Input
                {...register('description')}
                placeholder="Descrizione opzionale…"
              />
            </div>
          </div>

          {/* Caselle PEC reali */}
          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <Inbox className="h-4 w-4 text-primary" />
              <Label>Caselle PEC reali *</Label>
            </div>
            {availableMailboxes.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-4 border-2 border-dashed rounded-lg">
                Nessuna casella PEC disponibile. Configura prima una casella reale.
              </p>
            ) : (
              <div className="grid grid-cols-1 gap-2 max-h-44 overflow-y-auto border rounded-lg p-3">
                {availableMailboxes.map((mb) => {
                  const checked = (selectedMailboxIds ?? []).includes(mb.id)
                  return (
                    <label
                      key={mb.id}
                      className={cn(
                        'flex items-center gap-3 p-2.5 rounded-md border cursor-pointer transition-colors',
                        checked
                          ? 'border-primary bg-primary/5'
                          : 'border-transparent hover:bg-muted/50',
                      )}
                    >
                      <input
                        type="checkbox"
                        checked={checked}
                        onChange={() => toggleMailbox(mb.id)}
                        className="h-4 w-4 accent-primary"
                      />
                      <div className="min-w-0">
                        <p className="text-sm font-medium truncate">{mb.email_address}</p>
                        {mb.display_name && (
                          <p className="text-xs text-muted-foreground truncate">{mb.display_name}</p>
                        )}
                      </div>
                    </label>
                  )
                })}
              </div>
            )}
            {(selectedMailboxIds ?? []).length === 0 && availableMailboxes.length > 0 && (
              <p className="text-xs text-amber-600">
                Seleziona almeno una casella PEC reale da associare.
              </p>
            )}
          </div>

          {/* Regole */}
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <Label>Regole di filtro (combinate in AND)</Label>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() =>
                  append({ field: 'subject', operator: 'contains', value: '', date_from: '', date_to: '' })
                }
              >
                <Plus className="h-3.5 w-3.5 mr-1" />
                Aggiungi regola
              </Button>
            </div>

            {fields.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-4 border-2 border-dashed rounded-lg">
                Nessuna regola. La VBox mostrerà tutti i messaggi delle caselle selezionate.
              </p>
            ) : (
              <div className="space-y-2">
                {fields.map((field, index) => (
                  <div key={field.id} className="flex items-start gap-2 p-3 border rounded-lg bg-muted/30">
                    <div className="grid grid-cols-3 gap-2 flex-1">
                      {/* Campo */}
                      <div>
                        <label className="text-xs text-muted-foreground mb-1 block">Campo</label>
                        <select
                          className="w-full h-9 rounded-md border border-input bg-background px-2 text-sm"
                          {...register(`rules.${index}.field`)}
                        >
                          {(Object.entries(FIELD_LABELS) as [VBoxField, string][]).map(
                            ([val, lbl]) => (
                              <option key={val} value={val}>{lbl}</option>
                            ),
                          )}
                        </select>
                      </div>

                      {/* Operatore */}
                      <div>
                        <label className="text-xs text-muted-foreground mb-1 block">Operatore</label>
                        <select
                          className="w-full h-9 rounded-md border border-input bg-background px-2 text-sm"
                          {...register(`rules.${index}.operator`)}
                        >
                          {(Object.entries(OPERATOR_LABELS) as [VBoxOperator, string][]).map(
                            ([val, lbl]) => (
                              <option key={val} value={val}>{lbl}</option>
                            ),
                          )}
                        </select>
                      </div>

                      {/* Valore */}
                      <div>
                        <label className="text-xs text-muted-foreground mb-1 block">Valore</label>
                        <Input
                          {...register(`rules.${index}.value`, { required: true })}
                          placeholder="es. info@comune.it"
                          className="h-9"
                        />
                      </div>

                      {/* Date range */}
                      <div>
                        <label className="text-xs text-muted-foreground mb-1 block">Dal (opz.)</label>
                        <Input type="date" {...register(`rules.${index}.date_from`)} className="h-9" />
                      </div>
                      <div>
                        <label className="text-xs text-muted-foreground mb-1 block">Al (opz.)</label>
                        <Input type="date" {...register(`rules.${index}.date_to`)} className="h-9" />
                      </div>
                    </div>

                    <button
                      type="button"
                      onClick={() => remove(index)}
                      className="mt-5 p-1.5 rounded hover:bg-destructive/10 text-destructive"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>

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

// ─── Dialog assegnazione utenti ───────────────────────────────────────────────

interface AssignUsersDialogProps {
  vbox: VirtualBoxResponse
  onClose: () => void
  onSaved: () => void
}

function AssignUsersDialog({ vbox, onClose, onSaved }: AssignUsersDialogProps) {
  const queryClient = useQueryClient()

  const { data: usersData } = useQuery({
    queryKey: ['users'],
    queryFn: () => usersApi.list(1, 100),
  })

  const { data: assignedData, isLoading: loadingAssigned } = useQuery({
    queryKey: ['vbox-assignments', vbox.id],
    queryFn: () => virtualBoxesApi.listAssignedUsers(vbox.id),
  })

  const assignedIds = new Set((assignedData ?? []).map((a: AssignedUserResponse) => a.user_id))
  const users = (usersData?.items ?? []).filter(
    (u) => !u.is_active === false && !['super_admin', 'admin'].includes(u.role),
  )

  const assignMutation = useMutation({
    mutationFn: (userId: string) =>
      virtualBoxesApi.assignUsers(vbox.id, { user_ids: [userId] }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vbox-assignments', vbox.id] })
      toast.success('Utente assegnato')
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const unassignMutation = useMutation({
    mutationFn: (userId: string) => virtualBoxesApi.unassignUser(vbox.id, userId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vbox-assignments', vbox.id] })
      toast.success('Assegnazione rimossa')
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  return (
    <Dialog open onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>Assegna utenti – {vbox.name}</DialogTitle>
        </DialogHeader>

        {/* Riepilogo caselle */}
        {vbox.mailboxes.length > 0 && (
          <div className="flex flex-wrap gap-1 mt-2">
            <span className="text-xs text-muted-foreground mr-1">Caselle:</span>
            {vbox.mailboxes.map((mb) => (
              <span
                key={mb.id}
                className="inline-flex items-center gap-1 rounded-full bg-indigo-100 text-indigo-800 px-2 py-0.5 text-xs"
              >
                <Inbox className="h-3 w-3" />
                {mb.display_name ?? mb.email_address}
              </span>
            ))}
          </div>
        )}

        <div className="mt-4 space-y-2 max-h-80 overflow-y-auto">
          {loadingAssigned ? (
            <div className="flex justify-center py-6">
              <div className="h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent" />
            </div>
          ) : users.length === 0 ? (
            <p className="text-sm text-muted-foreground text-center py-4">
              Nessun operatore disponibile
            </p>
          ) : (
            users.map((user) => {
              const isAssigned = assignedIds.has(user.id)
              return (
                <div
                  key={user.id}
                  className="flex items-center justify-between p-3 border rounded-lg"
                >
                  <div>
                    <p className="text-sm font-medium">{user.full_name}</p>
                    <p className="text-xs text-muted-foreground">{user.email}</p>
                  </div>
                  <Button
                    variant={isAssigned ? 'destructive' : 'outline'}
                    size="sm"
                    onClick={() => {
                      if (isAssigned) unassignMutation.mutate(user.id)
                      else assignMutation.mutate(user.id)
                    }}
                    isLoading={assignMutation.isPending || unassignMutation.isPending}
                  >
                    {isAssigned ? 'Rimuovi' : 'Assegna'}
                  </Button>
                </div>
              )
            })
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={onClose}>Chiudi</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
