import { useParams, useNavigate } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  ArrowLeft,
  Star,
  Archive,
  Download,
  Reply,
  Forward,
  Paperclip,
  Mail,
  Send,
} from 'lucide-react'
import toast from 'react-hot-toast'
import { Button } from '@/components/ui/Button'
import { PecStateBadge, PecTypeBadge } from '@/components/PecBadge/PecBadge'
import { ReceiptTree } from '@/components/ReceiptTree/ReceiptTree'
import { messagesApi } from '@/api/messages.api'
import { formatDate, formatBytes, MAILBOX_STATUS_LABELS } from '@/lib/utils'
import { getErrorMessage } from '@/api/client'

export function MessageDetailPage() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const queryClient = useQueryClient()

  // Carica messaggio
  const {
    data: message,
    isLoading,
    error,
  } = useQuery({
    queryKey: ['message', id],
    queryFn: () => messagesApi.get(id!),
    enabled: !!id,
  })

  // Carica allegati
  const { data: attachments = [] } = useQuery({
    queryKey: ['attachments', id],
    queryFn: () => messagesApi.getAttachments(id!),
    enabled: !!id && !!message?.has_attachments,
  })

  // Carica ricevute (solo per messaggi outbound)
  const { data: receipts = [] } = useQuery({
    queryKey: ['receipts', id],
    queryFn: () => messagesApi.getReceipts(id!),
    enabled: !!id && message?.direction === 'outbound',
  })

  // Toggle stella
  const toggleStarMutation = useMutation({
    mutationFn: (starred: boolean) => messagesApi.toggleStar(id!, starred),
    onSuccess: (updated) => {
      queryClient.setQueryData(['message', id], updated)
      toast.success(updated.is_starred ? 'Aggiunto ai preferiti' : 'Rimosso dai preferiti')
    },
    onError: (error) => toast.error(getErrorMessage(error)),
  })

  // Archivia
  const archiveMutation = useMutation({
    mutationFn: () => messagesApi.archive(id!),
    onSuccess: () => {
      toast.success('Messaggio archiviato')
      navigate('/inbox')
    },
    onError: (error) => toast.error(getErrorMessage(error)),
  })

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

  if (error || !message) {
    return (
      <div className="flex flex-col items-center justify-center h-64 gap-4">
        <p className="text-muted-foreground">Messaggio non trovato</p>
        <Button variant="outline" onClick={() => navigate('/inbox')}>
          <ArrowLeft className="h-4 w-4 mr-2" />
          Torna alla posta
        </Button>
      </div>
    )
  }

  return (
    <div className="flex flex-col h-full">
      {/* Toolbar */}
      <div className="border-b bg-background px-6 py-3 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Button variant="ghost" size="icon" onClick={() => navigate(-1)}>
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <span className="text-sm text-muted-foreground">
            {message.direction === 'inbound' ? 'Posta in arrivo' : 'Posta inviata'}
          </span>
        </div>

        <div className="flex items-center gap-2">
          {/* Stella */}
          <Button
            variant="ghost"
            size="icon"
            onClick={() => toggleStarMutation.mutate(!message.is_starred)}
          >
            <Star
              className={`h-5 w-5 ${message.is_starred ? 'text-yellow-500 fill-yellow-500' : 'text-muted-foreground'}`}
            />
          </Button>

          {/* Archivia */}
          {!message.is_archived && (
            <Button
              variant="ghost"
              size="icon"
              onClick={() => archiveMutation.mutate()}
              title="Archivia"
            >
              <Archive className="h-5 w-5 text-muted-foreground" />
            </Button>
          )}

          {/* Rispondi (solo per messaggi inbound PEC certificata) */}
          {message.direction === 'inbound' && message.pec_type === 'posta_certificata' && (
            <Button
              variant="outline"
              size="sm"
              onClick={() =>
                navigate('/compose', {
                  state: { replyTo: message },
                })
              }
            >
              <Reply className="h-4 w-4 mr-1" />
              Rispondi
            </Button>
          )}
        </div>
      </div>

      {/* Contenuto */}
      <div className="flex-1 overflow-y-auto">
        <div className="max-w-4xl mx-auto px-6 py-8 space-y-6">
          {/* Intestazione messaggio */}
          <div className="space-y-4">
            <div className="flex items-start justify-between gap-4">
              <h1 className="text-2xl font-semibold text-foreground leading-tight">
                {message.subject || '(nessun oggetto)'}
              </h1>
              <div className="flex items-center gap-2 flex-shrink-0">
                <PecStateBadge state={message.state} />
                {message.pec_type !== 'posta_certificata' && (
                  <PecTypeBadge type={message.pec_type} />
                )}
              </div>
            </div>

            {/* Dettagli busta */}
            <div className="rounded-lg border bg-muted/30 p-4 space-y-2">
              <div className="grid grid-cols-[auto,1fr] gap-x-4 gap-y-1.5 text-sm">
                <span className="font-medium text-muted-foreground">
                  {message.direction === 'inbound' ? 'Da:' : 'A:'}
                </span>
                <span className="text-foreground font-medium">
                  {message.direction === 'inbound'
                    ? message.from_address
                    : message.to_addresses?.join(', ')}
                </span>

                {message.direction === 'outbound' && message.from_address && (
                  <>
                    <span className="font-medium text-muted-foreground">Da:</span>
                    <span>{message.from_address}</span>
                  </>
                )}

                {message.direction === 'inbound' && message.to_addresses?.length > 0 && (
                  <>
                    <span className="font-medium text-muted-foreground">A:</span>
                    <span>{message.to_addresses.join(', ')}</span>
                  </>
                )}

                {message.cc_addresses?.length > 0 && (
                  <>
                    <span className="font-medium text-muted-foreground">Cc:</span>
                    <span>{message.cc_addresses.join(', ')}</span>
                  </>
                )}

                <span className="font-medium text-muted-foreground">Data:</span>
                <span>{formatDate(message.received_at || message.sent_at || message.created_at)}</span>

                {message.size_bytes && (
                  <>
                    <span className="font-medium text-muted-foreground">Dimensione:</span>
                    <span>{formatBytes(message.size_bytes)}</span>
                  </>
                )}

                <span className="font-medium text-muted-foreground">Cartella:</span>
                <span className="font-mono text-xs">{message.imap_folder}</span>
              </div>
            </div>
          </div>

          {/* Corpo del messaggio */}
          {(message.body_html || message.body_text) && (
            <div className="space-y-2">
              <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
                Contenuto
              </h3>
              <div className="rounded-lg border bg-background p-6">
                {message.body_html ? (
                  <div
                    className="prose prose-sm max-w-none"
                    dangerouslySetInnerHTML={{ __html: message.body_html }}
                  />
                ) : (
                  <pre className="whitespace-pre-wrap text-sm font-sans text-foreground">
                    {message.body_text}
                  </pre>
                )}
              </div>
            </div>
          )}

          {/* Allegati */}
          {attachments.length > 0 && (
            <div className="space-y-2">
              <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-2">
                <Paperclip className="h-4 w-4" />
                Allegati ({attachments.length})
              </h3>
              <div className="grid gap-2 sm:grid-cols-2">
                {attachments.map((att) => (
                  <a
                    key={att.id}
                    href={messagesApi.getAttachmentUrl(message.id, att.id)}
                    download={att.filename}
                    className="flex items-center gap-3 rounded-lg border bg-background p-3 hover:bg-muted/50 transition-colors group"
                  >
                    <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
                      <Paperclip className="h-5 w-5 text-primary" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium truncate">{att.filename}</p>
                      <p className="text-xs text-muted-foreground">
                        {att.content_type || 'Tipo sconosciuto'} • {formatBytes(att.size_bytes)}
                      </p>
                    </div>
                    <Download className="h-4 w-4 text-muted-foreground group-hover:text-foreground flex-shrink-0" />
                  </a>
                ))}
              </div>
            </div>
          )}

          {/* Ricevute (solo per outbound) */}
          {message.direction === 'outbound' && (
            <div className="space-y-2">
              <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-2">
                <Send className="h-4 w-4" />
                Tracciamento invio
              </h3>
              <div className="rounded-lg border bg-background p-4">
                <ReceiptTree message={message} receipts={receipts} />
              </div>
            </div>
          )}

          {/* Messaggio originale per ricevute */}
          {message.direction === 'inbound' && message.pec_type !== 'posta_certificata' && (
            <div className="rounded-lg border border-blue-200 bg-blue-50 p-4">
              <div className="flex items-center gap-2 text-sm text-blue-700">
                <Mail className="h-4 w-4" />
                <span>
                  Questo è un messaggio automatico di tipo{' '}
                  <strong>
                    <PecTypeBadge type={message.pec_type} />
                  </strong>
                </span>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
