/**
 * InboxPage – visualizza la posta in arrivo, inviata, preferiti, archiviata o cestino.
 *
 * Modalita' (viewMode):
 *  - 'inbox'    → Posta in Arrivo (solo inbound, is_archived=false, is_trashed=false)
 *  - 'sent'     → Posta Inviata (solo outbound, is_archived=false, is_trashed=false)
 *  - 'starred'  → Preferiti (is_starred=true, is_trashed=false)
 *  - 'archived' → Archiviati (is_archived=true, is_trashed=false)
 *  - 'trash'    → Cestino (is_trashed=true)
 *
 * Funzionalita':
 *  - Selezione singola e multipla tramite checkbox
 *  - Barra azioni bulk (stella, archivia, cestino, segna da leggere, tag)
 *  - Pulsanti azione rapida su hover di ogni riga
 *  - "Segna come da leggere" e "Sposta nel cestino" solo fuori dalle Virtual Box
 */
import { useEffect, useState, useCallback } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import {
  Inbox,
  RefreshCw,
  Search,
  Star,
  Mail,
  MailOpen,
  Send,
  ChevronLeft,
  ChevronRight,
  Archive,
  ArchiveX,
  StarOff,
  CheckSquare,
  Square,
  X,
  Tag,
  Trash2,
  RotateCcw,
  MailX,
  SlidersHorizontal,
  ChevronDown,
  ChevronUp,
  ShieldCheck,
  ShieldX,
  FileText,
  Paperclip,
  AlignLeft,
} from 'lucide-react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { PecStateBadge } from '@/components/PecBadge/PecBadge'
import { TagBadgeList } from '@/components/TagManager/TagBadge'
import { TagSelector } from '@/components/TagManager/TagSelector'
import { useAuth } from '@/hooks/useAuth'
import { messagesApi } from '@/api/messages.api'
import { labelsApi } from '@/api/labels.api'
import { mailboxesApi } from '@/api/mailboxes.api'
import { virtualBoxesApi } from '@/api/virtual_boxes.api'
import { formatRelative, truncate } from '@/lib/utils'
import type { MessageResponse } from '@/types/api.types'
import { cn } from '@/lib/utils'
import { getErrorMessage } from '@/api/client'

// ─── Props ────────────────────────────────────────────────────────────────────

export type InboxViewMode = 'inbox' | 'sent' | 'starred' | 'archived' | 'trash' | 'conservation_pending' | 'conservation_archived'

interface InboxPageProps {
  viewMode: InboxViewMode
}

// ─── Componente principale ─────────────────────────────────────────────────────

export function InboxPage({ viewMode }: InboxPageProps) {
  const navigate = useNavigate()
  const queryClient = useQueryClient()

  const { mailboxId, vboxId } = useParams<{ mailboxId?: string; vboxId?: string }>()

  // true = stiamo navigando in una casella reale (non virtual box)
  const isMailboxMode = !vboxId

  // ── Ruolo utente per visibilita' pulsante Conservazione ─────────────────────
  const { isAdmin, isSupervisor } = useAuth()
  const canConserve = isAdmin || isSupervisor

  // ── Stato filtri locale ──────────────────────────────────────────────────────
  const [searchInput, setSearchInput] = useState('')
  const [debouncedSearch, setDebouncedSearch] = useState('')
  const [isReadFilter, setIsReadFilter] = useState<boolean | undefined>(undefined)
  const [isStarredFilter, setIsStarredFilter] = useState<boolean | undefined>(undefined)
  const [page, setPage] = useState(1)
  const PAGE_SIZE = 50

  // ── Filtri avanzati ──────────────────────────────────────────────────────────
  const [showAdvancedFilters, setShowAdvancedFilters] = useState(false)
  const [dateFrom, setDateFrom] = useState('')
  const [dateTo, setDateTo] = useState('')
  const [pecTypeFilter, setPecTypeFilter] = useState('')
  const [pecStateFilter, setPecStateFilter] = useState('')

  const activeAdvancedFiltersCount = [dateFrom, dateTo, pecTypeFilter, pecStateFilter].filter(Boolean).length

  // ── Stato selezione ─────────────────────────────────────────────────────────
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())

  // ── Stato dialog tag bulk ────────────────────────────────────────────────────
  const [showTagSelector, setShowTagSelector] = useState(false)

  useEffect(() => {
    setSearchInput('')
    setDebouncedSearch('')
    setIsReadFilter(undefined)
    setIsStarredFilter(undefined)
    setDateFrom('')
    setDateTo('')
    setPecTypeFilter('')
    setPecStateFilter('')
    setShowAdvancedFilters(false)
    setPage(1)
    setSelectedIds(new Set())
  }, [mailboxId, vboxId, viewMode])

  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearch(searchInput)
      setPage(1)
    }, 400)
    return () => clearTimeout(timer)
  }, [searchInput])

  // ── Caselle (per breadcrumb + badge) ────────────────────────────────────────
  const { data: mailboxesData } = useQuery({
    queryKey: ['mailboxes'],
    queryFn: () => mailboxesApi.list(),
    staleTime: 5 * 60 * 1000,
  })

  const currentMailbox = mailboxId
    ? mailboxesData?.items.find((m) => m.id === mailboxId)
    : undefined

  const { data: myVboxes = [] } = useQuery({
    queryKey: ['virtual-boxes', 'my'],
    queryFn: () => virtualBoxesApi.myVirtualBoxes(),
    staleTime: 5 * 60 * 1000,
    enabled: !!vboxId,
  })

  const currentVbox = vboxId
    ? myVboxes.find((v) => v.id === vboxId)
    : undefined

  // ── Reset pagina per filtri avanzati ─────────────────────────────────────────
  useEffect(() => {
    setPage(1)
  }, [dateFrom, dateTo, pecTypeFilter])

  // ── Query messaggi ───────────────────────────────────────────────────────────
  const queryFilters = (() => {
    const advancedBase = {
      vbox_id: vboxId,
      mailbox_id: mailboxId,
      search: debouncedSearch || undefined,
      pec_type: pecTypeFilter || undefined,
      state: pecStateFilter || undefined,
      date_from: dateFrom ? new Date(dateFrom).toISOString() : undefined,
      date_to: dateTo ? new Date(dateTo + 'T23:59:59').toISOString() : undefined,
      page,
      page_size: PAGE_SIZE,
    }
    switch (viewMode) {
      case 'inbox':
        return {
          ...advancedBase,
          direction: 'inbound' as const,
          is_read: isReadFilter,
          is_starred: isStarredFilter,
          is_archived: false,
          is_trashed: false,
        }
      case 'sent':
        return {
          ...advancedBase,
          direction: 'outbound' as const,
          is_starred: isStarredFilter,
          is_archived: false,
          is_trashed: false,
        }
      case 'starred':
        return {
          ...advancedBase,
          is_starred: true,
          is_archived: false,
          is_trashed: false,
        }
      case 'archived':
        return {
          ...advancedBase,
          is_archived: true,
          is_trashed: false,
        }
      case 'trash':
        return {
          ...advancedBase,
          is_trashed: true,
        }
      case 'conservation_pending':
        return {
          ...advancedBase,
          is_pending_conservation: true,
        }
      case 'conservation_archived':
        return {
          ...advancedBase,
          is_conserved: true,
        }
    }
  })()

  const {
    data: messagesData,
    isLoading,
    refetch,
    isRefetching,
  } = useQuery({
    queryKey: ['messages', queryFilters],
    queryFn: () => messagesApi.list(queryFilters),
    refetchInterval: 60_000,
  })

  const messages = messagesData?.items || []
  const total = messagesData?.total || 0
  const totalPages = Math.ceil(total / PAGE_SIZE)

  const invalidateMessages = useCallback(() => {
    queryClient.invalidateQueries({ queryKey: ['messages'] })
  }, [queryClient])

  // ── Segna come letto ─────────────────────────────────────────────────────────
  const markReadMutation = useMutation({
    mutationFn: messagesApi.markRead,
    onSuccess: (updatedMsg) => {
      queryClient.setQueryData(
        ['messages', queryFilters],
        (old: { items: MessageResponse[]; total: number } | undefined) => {
          if (!old) return old
          return {
            ...old,
            items: old.items.map((m) => (m.id === updatedMsg.id ? updatedMsg : m)),
          }
        },
      )
    },
  })

  // ── Segna come DA leggere (unread) ───────────────────────────────────────────
  const markUnreadMutation = useMutation({
    mutationFn: (id: string) => messagesApi.markUnread(id),
    onSuccess: (updatedMsg) => {
      queryClient.setQueryData(
        ['messages', queryFilters],
        (old: { items: MessageResponse[]; total: number } | undefined) => {
          if (!old) return old
          return {
            ...old,
            items: old.items.map((m) => (m.id === updatedMsg.id ? updatedMsg : m)),
          }
        },
      )
      toast.success('Messaggio segnato come da leggere')
    },
    onError: (error) => toast.error(getErrorMessage(error)),
  })

  // ── Toggle stella singolo ────────────────────────────────────────────────────
  const toggleStarMutation = useMutation({
    mutationFn: ({ id, starred }: { id: string; starred: boolean }) =>
      messagesApi.toggleStar(id, starred),
    onSuccess: (updatedMsg) => {
      queryClient.setQueryData(
        ['messages', queryFilters],
        (old: { items: MessageResponse[]; total: number } | undefined) => {
          if (!old) return old
          if (viewMode === 'starred' && !updatedMsg.is_starred) {
            return { ...old, items: old.items.filter((m) => m.id !== updatedMsg.id), total: old.total - 1 }
          }
          return { ...old, items: old.items.map((m) => (m.id === updatedMsg.id ? updatedMsg : m)) }
        },
      )
      invalidateMessages()
    },
    onError: (error) => toast.error(getErrorMessage(error)),
  })

  // ── Archivia/Dearchivia singolo ──────────────────────────────────────────────
  const archiveMutation = useMutation({
    mutationFn: ({ id, archived }: { id: string; archived: boolean }) =>
      archived ? messagesApi.archive(id) : messagesApi.unarchive(id),
    onSuccess: (updatedMsg, { archived }) => {
      queryClient.setQueryData(
        ['messages', queryFilters],
        (old: { items: MessageResponse[]; total: number } | undefined) => {
          if (!old) return old
          return { ...old, items: old.items.filter((m) => m.id !== updatedMsg.id), total: old.total - 1 }
        },
      )
      toast.success(archived ? 'Messaggio archiviato' : 'Messaggio ripristinato dalla posta')
      invalidateMessages()
    },
    onError: (error) => toast.error(getErrorMessage(error)),
  })

  // ── Cestino/Ripristina singolo ────────────────────────────────────────────────
  const trashMutation = useMutation({
    mutationFn: ({ id, trashed }: { id: string; trashed: boolean }) =>
      trashed ? messagesApi.trash(id) : messagesApi.untrash(id),
    onSuccess: (updatedMsg, { trashed }) => {
      queryClient.setQueryData(
        ['messages', queryFilters],
        (old: { items: MessageResponse[]; total: number } | undefined) => {
          if (!old) return old
          return { ...old, items: old.items.filter((m) => m.id !== updatedMsg.id), total: old.total - 1 }
        },
      )
      toast.success(trashed ? 'Messaggio spostato nel cestino' : 'Messaggio ripristinato dal cestino')
      invalidateMessages()
    },
    onError: (error) => toast.error(getErrorMessage(error)),
  })

  // ── Conservazione/Rimozione singolo ───────────────────────────────────────────
  const conserveMutation = useMutation({
    mutationFn: ({ id, conserve }: { id: string; conserve: boolean }) =>
      conserve ? messagesApi.conserve(id) : messagesApi.unconserve(id),
    onSuccess: (updatedMsg, { conserve }) => {
      queryClient.setQueryData(
        ['messages', queryFilters],
        (old: { items: MessageResponse[]; total: number } | undefined) => {
          if (!old) return old
          return { ...old, items: old.items.filter((m) => m.id !== updatedMsg.id), total: old.total - 1 }
        },
      )
      toast.success(conserve ? 'Messaggio inviato in Da Conservare' : 'Messaggio rimosso da Da Conservare')
      invalidateMessages()
    },
    onError: (error) => toast.error(getErrorMessage(error)),
  })

  // ── Azioni bulk ──────────────────────────────────────────────────────────────
  const bulkMutation = useMutation({
    mutationFn: messagesApi.bulkUpdate,
    onSuccess: (result, payload) => {
      invalidateMessages()
      setSelectedIds(new Set())
      const n = result.updated
      if (payload.is_read === false) toast.success(`${n} ${n === 1 ? 'messaggio segnato' : 'messaggi segnati'} come da leggere`)
      else if (payload.is_starred === true) toast.success(`${n} ${n === 1 ? 'messaggio aggiunto' : 'messaggi aggiunti'} ai preferiti`)
      else if (payload.is_starred === false) toast.success(`${n} ${n === 1 ? 'messaggio rimosso' : 'messaggi rimossi'} dai preferiti`)
      else if (payload.is_archived === true) toast.success(`${n} ${n === 1 ? 'messaggio archiviato' : 'messaggi archiviati'}`)
      else if (payload.is_archived === false) toast.success(`${n} ${n === 1 ? 'messaggio ripristinato' : 'messaggi ripristinati'}`)
      else if (payload.is_trashed === true) toast.success(`${n} ${n === 1 ? 'messaggio spostato nel cestino' : 'messaggi spostati nel cestino'}`)
      else if (payload.is_trashed === false) toast.success(`${n} ${n === 1 ? 'messaggio ripristinato dal cestino' : 'messaggi ripristinati dal cestino'}`)
      else if (payload.is_pending_conservation === true) toast.success(`${n} ${n === 1 ? 'messaggio inviato' : 'messaggi inviati'} in Da Conservare`)
      else if (payload.is_pending_conservation === false) toast.success(`${n} ${n === 1 ? 'messaggio rimosso' : 'messaggi rimossi'} da Da Conservare`)
    },
    onError: (error) => toast.error(getErrorMessage(error)),
  })

  // ── Bulk tag ─────────────────────────────────────────────────────────────────
  const bulkLabelMutation = useMutation({
    mutationFn: labelsApi.bulkLabels,
    onSuccess: (result, payload) => {
      invalidateMessages()
      setSelectedIds(new Set())
      setShowTagSelector(false)
      const n = result.updated
      if (payload.action === 'add') {
        toast.success(`Tag aggiunti a ${n} ${n === 1 ? 'messaggio' : 'messaggi'}`)
      } else {
        toast.success(`Tag rimossi da ${n} ${n === 1 ? 'messaggio' : 'messaggi'}`)
      }
    },
    onError: (error) => toast.error(getErrorMessage(error)),
  })

  const handleBulkTag = (labelIds: string[], action: 'add' | 'remove') => {
    bulkLabelMutation.mutate({
      message_ids: Array.from(selectedIds),
      label_ids: labelIds,
      action,
    })
  }

  const handleBulkMarkUnread = () =>
    bulkMutation.mutate({ ids: Array.from(selectedIds), is_read: false })
  const handleBulkStar = () =>
    bulkMutation.mutate({ ids: Array.from(selectedIds), is_starred: true })
  const handleBulkUnstar = () =>
    bulkMutation.mutate({ ids: Array.from(selectedIds), is_starred: false })
  const handleBulkArchive = () =>
    bulkMutation.mutate({ ids: Array.from(selectedIds), is_archived: true })
  const handleBulkUnarchive = () =>
    bulkMutation.mutate({ ids: Array.from(selectedIds), is_archived: false })
  const handleBulkTrash = () =>
    bulkMutation.mutate({ ids: Array.from(selectedIds), is_trashed: true })
  const handleBulkUntrash = () =>
    bulkMutation.mutate({ ids: Array.from(selectedIds), is_trashed: false })
  const handleBulkConserve = () =>
    bulkMutation.mutate({ ids: Array.from(selectedIds), is_pending_conservation: true })
  const handleBulkUnconserve = () =>
    bulkMutation.mutate({ ids: Array.from(selectedIds), is_pending_conservation: false })

  // ── Selezione ────────────────────────────────────────────────────────────────
  const handleToggleSelect = (id: string, e: React.MouseEvent) => {
    e.stopPropagation()
    setSelectedIds((prev) => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  const handleSelectAll = () => {
    if (selectedIds.size === messages.length) {
      setSelectedIds(new Set())
    } else {
      setSelectedIds(new Set(messages.map((m) => m.id)))
    }
  }

  const handleClearSelection = () => setSelectedIds(new Set())

  // ── Click su messaggio ───────────────────────────────────────────────────────
  const handleMessageClick = async (message: MessageResponse) => {
    if (!message.is_read && message.direction === 'inbound') {
      markReadMutation.mutate(message.id)
    }
    navigate(`/messages/${message.id}`)
  }

  const handleRefresh = async () => {
    try {
      await refetch()
      toast.success('Casella aggiornata')
    } catch (error) {
      toast.error(getErrorMessage(error))
    }
  }

  // ── Label e icone folder ────────────────────────────────────────────────────
  const isInbound = viewMode === 'inbox'
  const folderLabel =
    viewMode === 'inbox' ? 'Posta in Arrivo'
    : viewMode === 'sent' ? 'Posta Inviata'
    : viewMode === 'starred' ? 'Preferiti'
    : viewMode === 'archived' ? 'Archiviati'
    : viewMode === 'trash' ? 'Cestino'
    : viewMode === 'conservation_pending' ? 'Da Conservare'
    : 'Storico Conservazione'
  const FolderIcon =
    viewMode === 'inbox' ? Inbox
    : viewMode === 'sent' ? Send
    : viewMode === 'starred' ? Star
    : viewMode === 'archived' ? Archive
    : viewMode === 'trash' ? Trash2
    : ShieldCheck

  const selectedCount = selectedIds.size
  const allSelected = messages.length > 0 && selectedCount === messages.length
  const someSelected = selectedCount > 0

  // ── Render ───────────────────────────────────────────────────────────────────
  return (
    <div className="flex flex-col h-full">
      {/* ── Header ── */}
      <div className="border-b bg-background px-6 py-4">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-start gap-2">
            <FolderIcon className="h-5 w-5 text-primary mt-1 flex-shrink-0" />
            <div>
              {currentMailbox ? (
                <div className="flex items-center gap-1.5 flex-wrap">
                  <span className="text-sm font-medium text-muted-foreground">
                    {currentMailbox.display_name || currentMailbox.email_address}
                  </span>
                  <span className="text-muted-foreground/40 text-sm">›</span>
                  <h1 className="text-xl font-semibold">{folderLabel}</h1>
                </div>
              ) : currentVbox ? (
                <div className="flex items-center gap-1.5 flex-wrap">
                  <span className="text-sm font-medium text-purple-600">
                    {currentVbox.label || currentVbox.name}
                  </span>
                  <span className="text-muted-foreground/40 text-sm">›</span>
                  <h1 className="text-xl font-semibold">{folderLabel}</h1>
                </div>
              ) : (
                <h1 className="text-xl font-semibold">{folderLabel}</h1>
              )}
              {total > 0 && (
                <p className="text-xs text-muted-foreground mt-0.5">
                  {total} {total === 1 ? 'messaggio' : 'messaggi'}
                </p>
              )}
            </div>
          </div>

          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={handleRefresh}
              isLoading={isRefetching}
            >
              <RefreshCw className="h-4 w-4 mr-1" />
              Aggiorna
            </Button>
            {viewMode !== 'trash' && (
              <Button size="sm" onClick={() => navigate('/compose')}>
                <Send className="h-4 w-4 mr-1" />
                Nuova PEC
              </Button>
            )}
          </div>
        </div>

        {/* ── Filtri ── */}
        <div className="flex items-center gap-3 flex-wrap">
          <div className="relative flex-1 min-w-48">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder={
                isInbound ? 'Cerca per oggetto, mittente…' : 'Cerca per oggetto, destinatario…'
              }
              className="pl-9 h-9"
              value={searchInput}
              onChange={(e) => setSearchInput(e.target.value)}
            />
          </div>

          {viewMode === 'inbox' && (
            <Button
              variant={isReadFilter === false ? 'default' : 'outline'}
              size="sm"
              onClick={() => setIsReadFilter(isReadFilter === false ? undefined : false)}
              className="h-9 text-xs"
            >
              <Mail className="h-3.5 w-3.5 mr-1" />
              Non letti
            </Button>
          )}

          {(viewMode === 'inbox' || viewMode === 'sent') && (
            <Button
              variant={isStarredFilter === true ? 'default' : 'outline'}
              size="sm"
              onClick={() => setIsStarredFilter(isStarredFilter === true ? undefined : true)}
              className="h-9 text-xs"
            >
              <Star className="h-3.5 w-3.5 mr-1" />
              Preferiti
            </Button>
          )}

          {/* Pulsante filtri avanzati */}
          <Button
            variant="outline"
            size="sm"
            className={cn('h-9 text-xs', activeAdvancedFiltersCount > 0 && 'border-primary text-primary')}
            onClick={() => setShowAdvancedFilters(!showAdvancedFilters)}
          >
            <SlidersHorizontal className="h-3.5 w-3.5 mr-1" />
            Filtri
            {activeAdvancedFiltersCount > 0 && (
              <span className="ml-1.5 inline-flex items-center justify-center h-4 w-4 rounded-full bg-primary text-white text-[10px] font-bold">
                {activeAdvancedFiltersCount}
              </span>
            )}
            {showAdvancedFilters ? <ChevronUp className="h-3 w-3 ml-1" /> : <ChevronDown className="h-3 w-3 ml-1" />}
          </Button>
        </div>

        {/* ── Pannello filtri avanzati ── */}
        {showAdvancedFilters && (
          <div className="mt-3 bg-muted/40 rounded-lg border p-3 grid grid-cols-2 md:grid-cols-4 gap-3">
            {/* Data da */}
            <div>
              <label className="text-xs font-medium text-muted-foreground mb-1 block">Data da</label>
              <input
                type="date"
                className="w-full h-8 px-2 rounded-md border bg-background text-xs focus:outline-none focus:ring-2 focus:ring-ring"
                value={dateFrom}
                onChange={(e) => setDateFrom(e.target.value)}
              />
            </div>

            {/* Data a */}
            <div>
              <label className="text-xs font-medium text-muted-foreground mb-1 block">Data a</label>
              <input
                type="date"
                className="w-full h-8 px-2 rounded-md border bg-background text-xs focus:outline-none focus:ring-2 focus:ring-ring"
                value={dateTo}
                onChange={(e) => setDateTo(e.target.value)}
              />
            </div>

            {/* Tipo PEC */}
            <div>
              <label className="text-xs font-medium text-muted-foreground mb-1 block">Tipo PEC</label>
              <select
                className="w-full h-8 px-2 rounded-md border bg-background text-xs focus:outline-none focus:ring-2 focus:ring-ring"
                value={pecTypeFilter}
                onChange={(e) => setPecTypeFilter(e.target.value)}
              >
                <option value="">Tutti i tipi</option>
                <option value="posta_certificata">Posta certificata</option>
                <option value="accettazione">Accettazione</option>
                <option value="avvenuta_consegna">Avvenuta consegna</option>
                <option value="mancata_consegna">Mancata consegna</option>
                <option value="non_accettazione">Non accettazione</option>
                <option value="errore_consegna">Errore consegna</option>
              </select>
            </div>

            {/* Stato PEC */}
            <div>
              <label className="text-xs font-medium text-muted-foreground mb-1 block">Stato PEC</label>
              <select
                className="w-full h-8 px-2 rounded-md border bg-background text-xs focus:outline-none focus:ring-2 focus:ring-ring"
                value={pecStateFilter}
                onChange={(e) => setPecStateFilter(e.target.value)}
              >
                <option value="">Tutti gli stati</option>
                <option value="received">Ricevuto</option>
                <option value="sent">Inviato</option>
                <option value="accepted">Accettato</option>
                <option value="delivered">Consegnato</option>
                <option value="anomaly">Anomalia</option>
                <option value="failed">Fallito</option>
              </select>
            </div>

            {/* Reset filtri */}
            {activeAdvancedFiltersCount > 0 && (
              <div className="flex items-end col-span-2 md:col-span-1">
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-8 text-xs text-muted-foreground w-full"
                  onClick={() => { setDateFrom(''); setDateTo(''); setPecTypeFilter(''); setPecStateFilter('') }}
                >
                  <X className="h-3.5 w-3.5 mr-1" />
                  Azzera filtri
                </Button>
              </div>
            )}
          </div>
        )}
      </div>

      {/* ── Barra azioni bulk ── */}
      {someSelected && (
        <div className="border-b bg-blue-50 dark:bg-blue-950/30 px-6 py-2.5 flex items-center gap-3 flex-wrap">
          <div className="flex items-center gap-2">
            <button
              onClick={handleClearSelection}
              className="p-0.5 rounded hover:bg-blue-100 dark:hover:bg-blue-900 transition-colors"
              title="Deseleziona tutto"
            >
              <X className="h-4 w-4 text-blue-600" />
            </button>
            <span className="text-sm font-medium text-blue-700 dark:text-blue-300">
              {selectedCount} {selectedCount === 1 ? 'selezionato' : 'selezionati'}
            </span>
          </div>

          <div className="h-4 w-px bg-blue-200 dark:bg-blue-700" />

          {/* Segna come da leggere (solo in modalita' casella, non vbox) */}
          {isMailboxMode && viewMode !== 'trash' && (
            <Button
              variant="outline"
              size="sm"
              className="h-8 text-xs border-blue-200 hover:bg-blue-100 dark:border-blue-700"
              onClick={handleBulkMarkUnread}
              isLoading={bulkMutation.isPending}
            >
              <MailX className="h-3.5 w-3.5 mr-1" />
              Segna da leggere
            </Button>
          )}

          {/* Stella */}
          {viewMode !== 'starred' && viewMode !== 'trash' && (
            <Button
              variant="outline"
              size="sm"
              className="h-8 text-xs border-blue-200 hover:bg-blue-100 dark:border-blue-700"
              onClick={handleBulkStar}
              isLoading={bulkMutation.isPending}
            >
              <Star className="h-3.5 w-3.5 mr-1 text-yellow-500" />
              Aggiungi ai preferiti
            </Button>
          )}

          {viewMode === 'starred' && (
            <Button
              variant="outline"
              size="sm"
              className="h-8 text-xs border-blue-200 hover:bg-blue-100 dark:border-blue-700"
              onClick={handleBulkUnstar}
              isLoading={bulkMutation.isPending}
            >
              <StarOff className="h-3.5 w-3.5 mr-1" />
              Rimuovi dai preferiti
            </Button>
          )}

          {(viewMode === 'inbox' || viewMode === 'sent') && (
            <Button
              variant="outline"
              size="sm"
              className="h-8 text-xs border-blue-200 hover:bg-blue-100 dark:border-blue-700"
              onClick={handleBulkUnstar}
              isLoading={bulkMutation.isPending}
            >
              <StarOff className="h-3.5 w-3.5 mr-1" />
              Rimuovi dai preferiti
            </Button>
          )}

          {viewMode !== 'archived' && viewMode !== 'trash' && (
            <Button
              variant="outline"
              size="sm"
              className="h-8 text-xs border-blue-200 hover:bg-blue-100 dark:border-blue-700"
              onClick={handleBulkArchive}
              isLoading={bulkMutation.isPending}
            >
              <Archive className="h-3.5 w-3.5 mr-1" />
              Archivia
            </Button>
          )}

          {viewMode === 'archived' && (
            <Button
              variant="outline"
              size="sm"
              className="h-8 text-xs border-blue-200 hover:bg-blue-100 dark:border-blue-700"
              onClick={handleBulkUnarchive}
              isLoading={bulkMutation.isPending}
            >
              <ArchiveX className="h-3.5 w-3.5 mr-1" />
              Ripristina dalla posta
            </Button>
          )}

          {/* Cestino / Ripristina cestino (solo modalita' casella) */}
          {isMailboxMode && viewMode !== 'trash' && (
            <Button
              variant="outline"
              size="sm"
              className="h-8 text-xs border-red-200 hover:bg-red-50 dark:border-red-800 text-red-600"
              onClick={handleBulkTrash}
              isLoading={bulkMutation.isPending}
            >
              <Trash2 className="h-3.5 w-3.5 mr-1" />
              Cestino
            </Button>
          )}

          {isMailboxMode && viewMode === 'trash' && (
            <Button
              variant="outline"
              size="sm"
              className="h-8 text-xs border-blue-200 hover:bg-blue-100 dark:border-blue-700"
              onClick={handleBulkUntrash}
              isLoading={bulkMutation.isPending}
            >
              <RotateCcw className="h-3.5 w-3.5 mr-1" />
              Ripristina dal cestino
            </Button>
          )}

          {/* Tag */}
          {viewMode !== 'trash' && (
            <Button
              variant="outline"
              size="sm"
              className="h-8 text-xs border-blue-200 hover:bg-blue-100 dark:border-blue-700"
              onClick={() => setShowTagSelector(true)}
            >
              <Tag className="h-3.5 w-3.5 mr-1 text-primary" />
              Tag
            </Button>
          )}

          {/* Invia a Conservazione (solo admin/supervisor, non nelle viste conservazione) */}
          {canConserve && viewMode !== 'conservation_pending' && viewMode !== 'conservation_archived' && viewMode !== 'trash' && (
            <Button
              variant="outline"
              size="sm"
              className="h-8 text-xs border-teal-200 hover:bg-teal-50 dark:border-teal-800 text-teal-700"
              onClick={handleBulkConserve}
              isLoading={bulkMutation.isPending}
            >
              <ShieldCheck className="h-3.5 w-3.5 mr-1" />
              Invia a Conservazione
            </Button>
          )}

          {/* Rimuovi da Da Conservare */}
          {canConserve && viewMode === 'conservation_pending' && (
            <Button
              variant="outline"
              size="sm"
              className="h-8 text-xs border-orange-200 hover:bg-orange-50 dark:border-orange-800 text-orange-700"
              onClick={handleBulkUnconserve}
              isLoading={bulkMutation.isPending}
            >
              <ShieldX className="h-3.5 w-3.5 mr-1" />
              Rimuovi da Da Conservare
            </Button>
          )}
        </div>
      )}

      {/* ── Lista messaggi ── */}
      <div className="flex-1 overflow-y-auto">
        {isLoading ? (
          <div className="flex items-center justify-center h-64">
            <div className="flex flex-col items-center gap-3">
              <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
              <p className="text-sm text-muted-foreground">Caricamento messaggi…</p>
            </div>
          </div>
        ) : messages.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-64 text-center">
            <FolderIcon className="h-12 w-12 text-muted-foreground/30 mb-3" />
            <p className="text-muted-foreground font-medium">Nessun messaggio trovato</p>
            <p className="text-sm text-muted-foreground/70 mt-1">
              {debouncedSearch || isReadFilter !== undefined || isStarredFilter !== undefined
                ? 'Prova a modificare i filtri di ricerca'
                : viewMode === 'inbox'
                  ? 'La posta in arrivo e vuota'
                  : viewMode === 'sent'
                    ? 'Nessun messaggio inviato'
                    : viewMode === 'starred'
                      ? 'Nessun messaggio nei preferiti'
                      : viewMode === 'archived'
                        ? 'Nessun messaggio archiviato'
                        : 'Il cestino e vuoto'}
            </p>
          </div>
        ) : (
          <div className="divide-y">
            {messages.length > 0 && (
              <div className="flex items-center gap-3 px-6 py-2 bg-muted/20 border-b">
                <button
                  onClick={handleSelectAll}
                  className="flex items-center gap-2 text-xs text-muted-foreground hover:text-foreground transition-colors"
                >
                  {allSelected ? (
                    <CheckSquare className="h-4 w-4 text-primary" />
                  ) : (
                    <Square className="h-4 w-4" />
                  )}
                  <span>
                    {allSelected
                      ? 'Deseleziona tutti'
                      : `Seleziona tutti (${messages.length})`}
                  </span>
                </button>
              </div>
            )}

            {messages.map((message) => (
              <MessageRow
                key={message.id}
                message={message}
                viewMode={viewMode}
                isMailboxMode={isMailboxMode}
                canConserve={canConserve}
                isSelected={selectedIds.has(message.id)}
                onSelect={(e) => handleToggleSelect(message.id, e)}
                onClick={() => handleMessageClick(message)}
                onToggleStar={(e) => {
                  e.stopPropagation()
                  toggleStarMutation.mutate({ id: message.id, starred: !message.is_starred })
                }}
                onToggleArchive={(e) => {
                  e.stopPropagation()
                  archiveMutation.mutate({ id: message.id, archived: !message.is_archived })
                }}
                onMarkUnread={(e) => {
                  e.stopPropagation()
                  markUnreadMutation.mutate(message.id)
                }}
                onToggleTrash={(e) => {
                  e.stopPropagation()
                  trashMutation.mutate({ id: message.id, trashed: !message.is_trashed })
                }}
                onToggleConserve={(e) => {
                  e.stopPropagation()
                  conserveMutation.mutate({ id: message.id, conserve: !message.is_pending_conservation })
                }}
                mailboxName={
                  !mailboxId
                    ? mailboxesData?.items.find((m) => m.id === message.mailbox_id)?.email_address
                    : undefined
                }
                searchTerm={debouncedSearch || undefined}
              />
            ))}
          </div>
        )}
      </div>

      {/* ── Paginazione ── */}
      {totalPages > 1 && (
        <div className="border-t px-6 py-3 flex items-center justify-between">
          <p className="text-sm text-muted-foreground">
            Pagina {page} di {totalPages} ({total} messaggi)
          </p>
          <div className="flex gap-2">
            <Button
              variant="outline"
              size="sm"
              disabled={page <= 1}
              onClick={() => setPage((p) => p - 1)}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              size="sm"
              disabled={page >= totalPages}
              onClick={() => setPage((p) => p + 1)}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      {/* ── Dialog assegnazione tag bulk ── */}
      {showTagSelector && (
        <TagSelector
          mode="bulk"
          open={showTagSelector}
          onClose={() => setShowTagSelector(false)}
          messageCount={selectedCount}
          onApply={handleBulkTag}
          isApplying={bulkLabelMutation.isPending}
        />
      )}
    </div>
  )
}

// ─── Riga singolo messaggio ────────────────────────────────────────────────────

interface MessageRowProps {
  message: MessageResponse
  viewMode: InboxViewMode
  isMailboxMode: boolean
  isSelected: boolean
  canConserve: boolean
  onSelect: (e: React.MouseEvent) => void
  onClick: () => void
  onToggleStar: (e: React.MouseEvent) => void
  onToggleArchive: (e: React.MouseEvent) => void
  onMarkUnread: (e: React.MouseEvent) => void
  onToggleTrash: (e: React.MouseEvent) => void
  onToggleConserve: (e: React.MouseEvent) => void
  mailboxName?: string
  searchTerm?: string
}

function MessageRow({
  message,
  viewMode,
  isMailboxMode,
  isSelected,
  canConserve,
  onSelect,
  onClick,
  onToggleStar,
  onToggleArchive,
  onMarkUnread,
  onToggleTrash,
  onToggleConserve,
  mailboxName,
  searchTerm,
}: MessageRowProps) {
  const [hovered, setHovered] = useState(false)
  const isUnread = !message.is_read && message.direction === 'inbound'

  return (
    <div
      className={cn(
        'flex gap-3 px-4 py-3 cursor-pointer hover:bg-muted/50 transition-colors group',
        searchTerm ? 'items-start' : 'items-center',
        isUnread && 'bg-blue-50/50 dark:bg-blue-950/20',
        isSelected && 'bg-blue-100/60 dark:bg-blue-900/30',
      )}
      onClick={onClick}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      {/* ── Checkbox selezione ── */}
      <div
        className="flex-shrink-0 w-6 flex items-center justify-center"
        onClick={onSelect}
      >
        {isSelected ? (
          <CheckSquare className="h-4 w-4 text-primary" />
        ) : (
          <Square
            className={cn(
              'h-4 w-4 transition-opacity',
              hovered ? 'opacity-100 text-muted-foreground' : 'opacity-0',
            )}
          />
        )}
      </div>

      {/* ── Icona direzione ── */}
      <div className="flex-shrink-0">
        {message.direction === 'inbound' ? (
          isUnread ? (
            <Mail className="h-5 w-5 text-blue-600" />
          ) : (
            <MailOpen className="h-5 w-5 text-muted-foreground" />
          )
        ) : (
          <Send className="h-5 w-5 text-muted-foreground" />
        )}
      </div>

      {/* ── Contenuto ── */}
      <div className="flex-1 min-w-0">
        <div className="flex items-center justify-between gap-2">
          <div className="flex items-center gap-2 min-w-0">
            <span
              className={cn(
                'text-sm truncate',
                isUnread ? 'font-semibold text-foreground' : 'font-medium text-foreground',
              )}
            >
              {message.direction === 'inbound'
                ? (message.from_address || 'Mittente sconosciuto')
                : (message.to_addresses?.[0] || 'Destinatario sconosciuto')}
            </span>

            {mailboxName && (
              <span className="text-xs text-muted-foreground bg-muted px-1.5 py-0.5 rounded flex-shrink-0">
                {mailboxName}
              </span>
            )}
          </div>

          <div className="flex items-center gap-2 flex-shrink-0">
            <PecStateBadge state={message.state} />
            <span className="text-xs text-muted-foreground">
              {formatRelative(message.received_at || message.sent_at || message.created_at)}
            </span>
          </div>
        </div>

        <div className="flex items-center gap-2 mt-0.5">
          {isUnread && (
            <span className="h-2 w-2 rounded-full bg-blue-600 flex-shrink-0" />
          )}
          <p
            className={cn(
              'text-sm truncate',
              isUnread ? 'font-medium text-foreground' : 'text-muted-foreground',
            )}
          >
            {message.subject || '(nessun oggetto)'}
          </p>
        </div>

        {message.labels && message.labels.length > 0 && (
          <div className="mt-1" onClick={(e) => e.stopPropagation()}>
            <TagBadgeList labels={message.labels} maxVisible={4} size="sm" />
          </div>
        )}

        {message.body_text && (
          <p className="text-xs text-muted-foreground truncate mt-0.5">
            {truncate(message.body_text, 120)}
          </p>
        )}

        {/* Badge "Trovato in" (solo durante ricerca attiva con match info) */}
        {searchTerm && message.search_match && (
          <div className="flex items-center flex-wrap gap-1 mt-1.5">
            <span className="text-xs text-muted-foreground mr-0.5">Trovato in:</span>
            {message.search_match.in_subject && (
              <span className="inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 font-medium">
                <FileText className="h-3 w-3" />
                Oggetto
              </span>
            )}
            {message.search_match.in_body && (
              <span className="inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300 font-medium">
                <AlignLeft className="h-3 w-3" />
                Corpo del messaggio
              </span>
            )}
            {message.search_match.in_attachments.map((att) => (
              <span
                key={att.id}
                className="inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300 font-medium max-w-[200px]"
                title={att.filename}
              >
                <Paperclip className="h-3 w-3 flex-shrink-0" />
                <span className="truncate">{att.filename}</span>
              </span>
            ))}
          </div>
        )}
      </div>

      {/* ── Azioni rapide (visibili su hover) ── */}
      <div className="flex items-center gap-1 flex-shrink-0">
        {/* Stella */}
        <button
          onClick={onToggleStar}
          title={message.is_starred ? 'Rimuovi dai preferiti' : 'Aggiungi ai preferiti'}
          className={cn(
            'p-1 rounded hover:bg-muted transition-all',
            message.is_starred
              ? 'opacity-100'
              : hovered
                ? 'opacity-100'
                : 'opacity-0 pointer-events-none',
          )}
        >
          <Star
            className={cn(
              'h-4 w-4',
              message.is_starred ? 'text-yellow-500 fill-yellow-500' : 'text-muted-foreground',
            )}
          />
        </button>

        {/* Segna come da leggere (solo in modalita' casella, solo messaggi gia' letti) */}
        {isMailboxMode && message.is_read && viewMode !== 'trash' && (
          <button
            onClick={onMarkUnread}
            title="Segna come da leggere"
            className={cn(
              'p-1 rounded hover:bg-muted transition-all',
              hovered ? 'opacity-100' : 'opacity-0 pointer-events-none',
            )}
          >
            <MailX className="h-4 w-4 text-muted-foreground" />
          </button>
        )}

        {/* Archivia/Ripristina (non nel cestino) */}
        {viewMode !== 'trash' && (
          <button
            onClick={onToggleArchive}
            title={viewMode === 'archived' ? 'Ripristina dalla posta' : 'Archivia'}
            className={cn(
              'p-1 rounded hover:bg-muted transition-all',
              hovered ? 'opacity-100' : 'opacity-0 pointer-events-none',
            )}
          >
            {viewMode === 'archived' ? (
              <ArchiveX className="h-4 w-4 text-muted-foreground" />
            ) : (
              <Archive className="h-4 w-4 text-muted-foreground" />
            )}
          </button>
        )}

        {/* Cestino / Ripristina dal cestino (solo in modalita' casella) */}
        {isMailboxMode && (
          <button
            onClick={onToggleTrash}
            title={viewMode === 'trash' ? 'Ripristina dal cestino' : 'Sposta nel cestino'}
            className={cn(
              'p-1 rounded hover:bg-muted transition-all',
              hovered ? 'opacity-100' : 'opacity-0 pointer-events-none',
            )}
          >
            {viewMode === 'trash' ? (
              <RotateCcw className="h-4 w-4 text-muted-foreground" />
            ) : (
              <Trash2 className="h-4 w-4 text-muted-foreground" />
            )}
          </button>
        )}

        {/* Invia a Conservazione / Rimuovi da Da Conservare */}
        {canConserve && viewMode !== 'trash' && viewMode !== 'conservation_archived' && (
          <button
            onClick={onToggleConserve}
            title={viewMode === 'conservation_pending' ? 'Rimuovi da Da Conservare' : 'Invia a Conservazione'}
            className={cn(
              'p-1 rounded hover:bg-muted transition-all',
              message.is_pending_conservation
                ? 'opacity-100'
                : hovered
                  ? 'opacity-100'
                  : 'opacity-0 pointer-events-none',
            )}
          >
            {viewMode === 'conservation_pending' ? (
              <ShieldX className="h-4 w-4 text-orange-500" />
            ) : (
              <ShieldCheck
                className={cn(
                  'h-4 w-4',
                  message.is_pending_conservation ? 'text-teal-600' : 'text-muted-foreground',
                )}
              />
            )}
          </button>
        )}

        {/* Indicatore allegati */}
        {message.has_attachments && (
          <span className="text-xs text-muted-foreground"></span>
        )}
      </div>
    </div>
  )
}
