import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  Inbox,
  RefreshCw,
  Search,
  Star,
  Mail,
  MailOpen,
  Filter,
  Send,
  ChevronLeft,
  ChevronRight,
} 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 { messagesApi } from '@/api/messages.api'
import { mailboxesApi } from '@/api/mailboxes.api'
import { useInboxStore } from '@/store/inbox.store'
import { formatRelative, truncate } from '@/lib/utils'
import type { MessageResponse } from '@/types/api.types'
import { cn } from '@/lib/utils'
import { getErrorMessage } from '@/api/client'

export function InboxPage() {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const { filters, setFilters } = useInboxStore()
  const [searchInput, setSearchInput] = useState('')
  const [selectedDirection, setSelectedDirection] = useState<'all' | 'inbound' | 'outbound'>('all')

  // Carica caselle per il filtro
  const { data: mailboxesData } = useQuery({
    queryKey: ['mailboxes'],
    queryFn: () => mailboxesApi.list(),
  })

  // Carica messaggi
  const {
    data: messagesData,
    isLoading,
    refetch,
    isRefetching,
  } = useQuery({
    queryKey: ['messages', filters],
    queryFn: () =>
      messagesApi.list({
        ...filters,
        direction: selectedDirection === 'all' ? undefined : selectedDirection,
        search: searchInput || undefined,
      }),
    refetchInterval: 60000, // refresh ogni minuto
  })

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

  // Gestione ricerca con debounce
  useEffect(() => {
    const timer = setTimeout(() => {
      setFilters({ search: searchInput || undefined, page: 1 })
    }, 400)
    return () => clearTimeout(timer)
  }, [searchInput, setFilters])

  const handleMessageClick = async (message: MessageResponse) => {
    if (!message.is_read) {
      markReadMutation.mutate(message.id)
    }
    navigate(`/messages/${message.id}`)
  }

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

  const messages = messagesData?.items || []
  const total = messagesData?.total || 0
  const currentPage = filters.page || 1
  const pageSize = filters.page_size || 50
  const totalPages = Math.ceil(total / pageSize)

  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-center gap-2">
            <Inbox className="h-5 w-5 text-primary" />
            <h1 className="text-xl font-semibold">Posta</h1>
            {total > 0 && (
              <span className="text-sm text-muted-foreground">({total} messaggi)</span>
            )}
          </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>
            <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">
          {/* Barra di ricerca */}
          <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="Cerca per oggetto, mittente..."
              className="pl-9 h-9"
              value={searchInput}
              onChange={(e) => setSearchInput(e.target.value)}
            />
          </div>

          {/* Filtro direzione */}
          <div className="flex gap-1 p-1 rounded-lg bg-muted">
            {(['all', 'inbound', 'outbound'] as const).map((d) => (
              <button
                key={d}
                onClick={() => {
                  setSelectedDirection(d)
                  setFilters({ direction: d === 'all' ? undefined : d, page: 1 })
                }}
                className={cn(
                  'px-3 py-1 rounded-md text-xs font-medium transition-colors',
                  selectedDirection === d
                    ? 'bg-background text-foreground shadow-sm'
                    : 'text-muted-foreground hover:text-foreground',
                )}
              >
                {d === 'all' ? 'Tutti' : d === 'inbound' ? '📥 In arrivo' : '📤 Inviati'}
              </button>
            ))}
          </div>

          {/* Filtro casella */}
          {mailboxesData?.items && mailboxesData.items.length > 1 && (
            <select
              className="h-9 rounded-md border border-input bg-background px-3 text-sm"
              value={filters.mailbox_id || ''}
              onChange={(e) => setFilters({ mailbox_id: e.target.value || undefined, page: 1 })}
            >
              <option value="">Tutte le caselle</option>
              {mailboxesData.items.map((mb) => (
                <option key={mb.id} value={mb.id}>
                  {mb.display_name || mb.email_address}
                </option>
              ))}
            </select>
          )}

          {/* Filtro letti/non letti */}
          <div className="flex gap-1">
            <Button
              variant={filters.is_read === false ? 'default' : 'outline'}
              size="sm"
              onClick={() =>
                setFilters({ is_read: filters.is_read === false ? undefined : false })
              }
              className="h-9 text-xs"
            >
              <Mail className="h-3.5 w-3.5 mr-1" />
              Non letti
            </Button>
            <Button
              variant={filters.is_starred === true ? 'default' : 'outline'}
              size="sm"
              onClick={() =>
                setFilters({ is_starred: filters.is_starred === true ? undefined : true })
              }
              className="h-9 text-xs"
            >
              <Star className="h-3.5 w-3.5 mr-1" />
              Preferiti
            </Button>
          </div>
        </div>
      </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">
            <Inbox 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">
              {searchInput ? 'Prova a modificare i filtri di ricerca' : 'La casella è vuota'}
            </p>
          </div>
        ) : (
          <div className="divide-y">
            {messages.map((message) => (
              <MessageRow
                key={message.id}
                message={message}
                onClick={() => handleMessageClick(message)}
                mailboxName={
                  mailboxesData?.items.find((m) => m.id === message.mailbox_id)
                    ?.email_address
                }
              />
            ))}
          </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 {currentPage} di {totalPages} ({total} messaggi)
          </p>
          <div className="flex gap-2">
            <Button
              variant="outline"
              size="sm"
              disabled={currentPage <= 1}
              onClick={() => setFilters({ page: currentPage - 1 })}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              size="sm"
              disabled={currentPage >= totalPages}
              onClick={() => setFilters({ page: currentPage + 1 })}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}
    </div>
  )
}

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

interface MessageRowProps {
  message: MessageResponse
  onClick: () => void
  mailboxName?: string
}

function MessageRow({ message, onClick, mailboxName }: MessageRowProps) {
  const isUnread = !message.is_read && message.direction === 'inbound'

  return (
    <div
      className={cn(
        'flex items-start gap-3 px-6 py-4 cursor-pointer hover:bg-muted/50 transition-colors',
        isUnread && 'bg-blue-50/50',
      )}
      onClick={onClick}
    >
      {/* Icona direzione */}
      <div className="mt-1 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 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.body_text && (
          <p className="text-xs text-muted-foreground truncate mt-0.5">
            {truncate(message.body_text, 120)}
          </p>
        )}
      </div>

      {/* Indicatori */}
      <div className="flex flex-col items-center gap-1 flex-shrink-0">
        {message.is_starred && <Star className="h-4 w-4 text-yellow-500 fill-yellow-500" />}
        {message.has_attachments && (
          <span className="text-xs text-muted-foreground">📎</span>
        )}
      </div>
    </div>
  )
}
