import { useState, useRef, useMemo, useEffect } from 'react'
import { useForm, useFieldArray, useWatch } from 'react-hook-form'
import {
  Send,
  X,
  Plus,
  AlertCircle,
  Paperclip,
  Upload,
  Filter,
  Minus,
  Maximize2,
  Minimize2,
  FileText,
  ChevronDown,
} from 'lucide-react'
import { useQuery, useMutation } from '@tanstack/react-query'
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 { RichTextEditor } from '@/components/RichTextEditor/RichTextEditor'
import { ContactPickerPopover } from '@/components/ComposeModal/ContactPickerPopover'
import { sendApi } from '@/api/send.api'
import { mailboxesApi } from '@/api/mailboxes.api'
import { virtualBoxesApi } from '@/api/virtual_boxes.api'
import { signaturesApi } from '@/api/signatures.api'
import { templatesApi } from '@/api/templates.api'
import type { TemplateResponse } from '@/api/templates.api'
import { getErrorMessage } from '@/api/client'
import { useComposeStore } from '@/store/compose.store'
import type { MessageResponse } from '@/types/api.types'

// ─── Utilita' firma ───────────────────────────────────────────────────────────

const SIG_ATTR = 'data-pechub-sig'

/** Rimuove il blocco firma esistente e (opzionalmente) ne inserisce uno nuovo. */
function injectSignature(body: string, sigHtml: string | null): string {
  const withoutSig = body.replace(
    new RegExp(`<div[^>]*${SIG_ATTR}="1"[^>]*>[\\s\\S]*?<\\/div>`, 'g'),
    ''
  )
  if (!sigHtml) return withoutSig
  const sigBlock = `<div ${SIG_ATTR}="1" style="margin-top:12px;padding-top:8px;border-top:1px solid #d1d5db">${sigHtml}</div>`
  if (withoutSig.includes('<hr>')) {
    return withoutSig.replace('<hr>', sigBlock + '<hr>')
  }
  // Se il corpo e' vuoto (nuova PEC), anteponi un paragrafo vuoto sopra la firma
  // cosi' il cursore si posiziona sopra di essa e non dentro/dopo
  const content = withoutSig.trim() ? withoutSig : '<p></p>'
  return content + sigBlock
}

// ─── Tipi ─────────────────────────────────────────────────────────────────────

interface MailboxSelectItem {
  id: string
  email_address: string
  display_name: string | null
  status: string
  fromVbox?: boolean
}

interface ComposeFormValues {
  mailbox_id: string
  to_addresses: { value: string }[]
  cc_addresses: { value: string }[]
  subject: string
}

// ─── Utility ──────────────────────────────────────────────────────────────────

const MAX_FILE_SIZE = 20 * 1024 * 1024

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}

function htmlToText(html: string): string {
  if (!html || html === '<p></p>') return ''
  const div = document.createElement('div')
  div.innerHTML = html
  return div.textContent || div.innerText || ''
}

function buildInitialBody(replyTo?: MessageResponse | null, forwardOf?: MessageResponse | null): string {
  if (replyTo) {
    const date = new Date(replyTo.received_at || replyTo.created_at).toLocaleDateString('it-IT')
    return [
      '<p></p>',
      '<p></p>',
      '<hr>',
      `<p><strong>In risposta al messaggio del ${date}</strong></p>`,
      `<p>Da: ${replyTo.from_address || ''}</p>`,
      `<p>A: ${replyTo.to_addresses?.join(', ') || ''}</p>`,
      `<p>Oggetto: ${replyTo.subject || ''}</p>`,
    ].join('')
  }
  if (forwardOf) {
    const date = new Date(forwardOf.received_at || forwardOf.sent_at || forwardOf.created_at).toLocaleDateString('it-IT')
    const bodyContent = forwardOf.body_text
      ? `<pre style="white-space:pre-wrap;font-family:inherit">${forwardOf.body_text}</pre>`
      : ''
    return [
      '<p></p>',
      '<p></p>',
      '<hr>',
      `<p><strong>Messaggio inoltrato</strong></p>`,
      `<p>Da: ${forwardOf.from_address || ''}</p>`,
      `<p>A: ${forwardOf.to_addresses?.join(', ') || ''}</p>`,
      `<p>Data: ${date}</p>`,
      `<p>Oggetto: ${forwardOf.subject || ''}</p>`,
      bodyContent,
    ].join('')
  }
  return ''
}

/**
 * Calcola i destinatari iniziali per "Rispondi a tutti":
 * from + tutti i to, deduplicati (la propria email verra' filtrata dopo che le caselle si caricano).
 */
function buildReplyAllToAddresses(replyTo: MessageResponse): { value: string }[] {
  const seen = new Set<string>()
  const result: { value: string }[] = []
  const addIfNew = (addr: string) => {
    const normalized = addr.trim().toLowerCase()
    if (normalized && !seen.has(normalized)) {
      seen.add(normalized)
      result.push({ value: addr.trim() })
    }
  }
  if (replyTo.from_address) addIfNew(replyTo.from_address)
  for (const addr of replyTo.to_addresses || []) addIfNew(addr)
  return result.length > 0 ? result : [{ value: '' }]
}

// ─── Form interno (rimontato ogni volta che cambia il messaggio) ───────────────

interface ComposeFormProps {
  replyTo: MessageResponse | null
  forwardOf: MessageResponse | null
  replyAll: boolean
  onClose: () => void
}

function ComposeForm({ replyTo, forwardOf, replyAll, onClose }: ComposeFormProps) {
  const fileInputRef = useRef<HTMLInputElement>(null)

  // In modalita' "rispondi a tutti" apri CC automaticamente se ci sono CC originali
  const [showCc, setShowCc] = useState(
    replyAll && (replyTo?.cc_addresses?.length ?? 0) > 0
  )
  const [attachments, setAttachments] = useState<File[]>([])
  const [bodyHtml, setBodyHtml] = useState<string>(() =>
    buildInitialBody(replyTo, forwardOf)
  )

  // Flag per eseguire il filtro della propria email una sola volta dopo il caricamento delle caselle
  const ownEmailFilteredRef = useRef(false)

  const buildDefaultTo = (): { value: string }[] => {
    if (replyAll && replyTo) return buildReplyAllToAddresses(replyTo)
    if (replyTo) return [{ value: replyTo.from_address || '' }]
    return [{ value: '' }]
  }

  const buildDefaultCc = (): { value: string }[] => {
    if (replyAll && replyTo && replyTo.cc_addresses?.length > 0) {
      return replyTo.cc_addresses.map((a) => ({ value: a }))
    }
    return []
  }

  const {
    register,
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<ComposeFormValues>({
    defaultValues: {
      mailbox_id: replyTo?.mailbox_id || forwardOf?.mailbox_id || '',
      to_addresses: buildDefaultTo(),
      cc_addresses: buildDefaultCc(),
      subject: replyTo
        ? `Re: ${replyTo.subject || ''}`
        : forwardOf
          ? `Fwd: ${forwardOf.subject || ''}`
          : '',
    },
  })

  const { fields: toFields, append: appendTo, remove: removeTo, replace: replaceTo } = useFieldArray({ control, name: 'to_addresses' })
  const { fields: ccFields, append: appendCc, remove: removeCc } = useFieldArray({ control, name: 'cc_addresses' })

  // ── Auto-inserimento firma ────────────────────────────────────────────────
  const watchedMailboxId = useWatch({ control, name: 'mailbox_id' })
  const signatureContext = replyTo ? 'reply' : 'compose'
  const sigHtmlRef = useRef<string | null>(null)

  useEffect(() => {
    if (!watchedMailboxId) {
      sigHtmlRef.current = null
      setBodyHtml((prev) => injectSignature(prev, null))
      return
    }
    signaturesApi
      .resolve({ context: signatureContext, mailbox_id: watchedMailboxId })
      .then((sig) => {
        sigHtmlRef.current = sig?.body_html ?? null
        setBodyHtml((prev) => injectSignature(prev, sig?.body_html ?? null))
      })
      .catch(() => {
        sigHtmlRef.current = null
      })
  }, [watchedMailboxId, signatureContext])
  // ─────────────────────────────────────────────────────────────────────────

  // ── Selettore template ────────────────────────────────────────────────────
  const [showTemplatePicker, setShowTemplatePicker] = useState(false)

  const { data: templatesData, isLoading: templatesLoading } = useQuery({
    queryKey: ['templates'],
    queryFn: () => templatesApi.list(),
    enabled: showTemplatePicker,
    staleTime: 60 * 1000,
  })

  const applyTemplate = (tpl: TemplateResponse) => {
    const hrIndex = bodyHtml.indexOf('<hr>')
    const quotedPart = hrIndex >= 0 ? bodyHtml.slice(hrIndex) : ''
    const templateBody = tpl.body_html || (tpl.body_text ? `<p>${tpl.body_text}</p>` : '')
    const newBodyBase = templateBody + quotedPart
    setBodyHtml(injectSignature(newBodyBase, sigHtmlRef.current))
    if (!replyTo && !forwardOf && tpl.subject) {
      setValue('subject', tpl.subject)
    }
    setShowTemplatePicker(false)
    toast.success(`Template "${tpl.name}" applicato`)
  }
  // ─────────────────────────────────────────────────────────────────────────

  const { data: mailboxesData, isLoading: mailboxesLoading } = useQuery({
    queryKey: ['mailboxes'],
    queryFn: () => mailboxesApi.list(),
  })

  const { data: vboxMailboxes = [], isLoading: vboxMailboxesLoading } = useQuery({
    queryKey: ['virtual-boxes', 'my-mailboxes'],
    queryFn: () => virtualBoxesApi.getMyMailboxes(),
  })

  const activeCaselle = useMemo((): MailboxSelectItem[] => {
    const regularActive: MailboxSelectItem[] = (
      mailboxesData?.items.filter((m) => m.status === 'active') || []
    ).map((m) => ({
      id: m.id,
      email_address: m.email_address,
      display_name: m.display_name,
      status: m.status,
      fromVbox: false,
    }))

    const regularIds = new Set(regularActive.map((m) => m.id))

    const vboxActive: MailboxSelectItem[] = vboxMailboxes
      .filter((m) => m.status === 'active' && !regularIds.has(m.id))
      .map((m) => ({
        id: m.id,
        email_address: m.email_address,
        display_name: m.display_name,
        status: m.status,
        fromVbox: true,
      }))

    return [...regularActive, ...vboxActive]
  }, [mailboxesData, vboxMailboxes])

  const isLoadingMailboxes = mailboxesLoading || vboxMailboxesLoading

  // ── Filtro propria email per "Rispondi a tutti" ───────────────────────────
  // Eseguito una sola volta dopo che le caselle si caricano e la mailbox e' selezionata
  useEffect(() => {
    if (!replyAll || !replyTo || isLoadingMailboxes || !watchedMailboxId || ownEmailFilteredRef.current) return
    const ownMailbox = activeCaselle.find((m) => m.id === watchedMailboxId)
    if (!ownMailbox) return
    ownEmailFilteredRef.current = true
    const ownEmail = ownMailbox.email_address.toLowerCase()
    const current = toFields.map((f) => f.value)
    const filtered = current.filter((v) => v.toLowerCase() !== ownEmail)
    if (filtered.length === 0) filtered.push('')
    replaceTo(filtered.map((v) => ({ value: v })))
  }, [replyAll, replyTo, isLoadingMailboxes, watchedMailboxId, activeCaselle, toFields, replaceTo])
  // ─────────────────────────────────────────────────────────────────────────

  const sendMutation = useMutation({
    mutationFn: (args: { data: Parameters<typeof sendApi.sendMultipart>[0]; files: File[] }) =>
      sendApi.sendMultipart(args.data, args.files),
    onSuccess: (job) => {
      toast.success(`PEC inviata! Job ID: ${job.id.slice(0, 8)}...`)
      onClose()
    },
    onError: (error) => {
      toast.error(getErrorMessage(error))
    },
  })

  const handleFileAdd = (files: FileList | null) => {
    if (!files) return
    const valid: File[] = []
    for (const file of Array.from(files)) {
      if (file.size > MAX_FILE_SIZE) {
        toast.error(`"${file.name}" supera il limite di 20 MB`)
      } else {
        valid.push(file)
      }
    }
    if (valid.length) setAttachments((prev) => [...prev, ...valid])
  }

  const removeAttachment = (idx: number) => {
    setAttachments((prev) => prev.filter((_, i) => i !== idx))
  }

  const onSubmit = async (formData: ComposeFormValues) => {
    const toAddresses = formData.to_addresses.map((t) => t.value.trim()).filter((v) => v.length > 0)
    if (toAddresses.length === 0) {
      toast.error('Inserisci almeno un destinatario')
      return
    }
    await sendMutation.mutateAsync({
      data: {
        mailbox_id: formData.mailbox_id,
        to_addresses: toAddresses,
        cc_addresses: formData.cc_addresses.map((c) => c.value.trim()).filter((v) => v.length > 0),
        subject: formData.subject,
        body_text: htmlToText(bodyHtml),
        body_html: bodyHtml,
        reply_to_message_id: replyTo?.id,
      },
      files: attachments,
    })
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} noValidate className="flex flex-col gap-0 h-full">
      {/* Corpo scrollabile */}
      <div className="flex-1 overflow-y-auto px-4 py-3 space-y-3">
        {/* Avviso informativo */}
        <div className="rounded-md border border-blue-200 bg-blue-50 p-2.5 flex items-start gap-2">
          <AlertCircle className="h-3.5 w-3.5 text-blue-600 mt-0.5 flex-shrink-0" />
          <p className="text-xs text-blue-700">
            L'invio avviene tramite il server PEC della casella selezionata.
          </p>
        </div>

        {/* Allegati del messaggio inoltrato */}
        {forwardOf && forwardOf.has_attachments && (
          <div className="rounded-md border border-amber-200 bg-amber-50 p-2.5 flex items-start gap-2">
            <Paperclip className="h-3.5 w-3.5 text-amber-600 mt-0.5 flex-shrink-0" />
            <p className="text-xs text-amber-700">
              Il messaggio originale contiene allegati. Scaricali e aggiungili qui manualmente.
            </p>
          </div>
        )}

        {/* Casella mittente */}
        <div className="space-y-1">
          <Label className="text-xs">Casella mittente *</Label>
          {isLoadingMailboxes ? (
            <div className="h-8 rounded-md border bg-muted animate-pulse" />
          ) : activeCaselle.length === 0 ? (
            <div className="rounded-md border border-destructive/50 bg-destructive/10 p-2 text-xs text-destructive">
              Nessuna casella PEC attiva disponibile.
            </div>
          ) : (
            <>
              <select
                className="flex h-8 w-full rounded-md border border-input bg-background px-3 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                {...register('mailbox_id', { required: 'Seleziona una casella mittente' })}
              >
                <option value="">Seleziona casella...</option>
                {activeCaselle.map((mb) => (
                  <option key={mb.id} value={mb.id}>
                    {mb.fromVbox ? ' ' : ''}{mb.display_name || mb.email_address} ({mb.email_address})
                  </option>
                ))}
              </select>
              {activeCaselle.some((m) => m.fromVbox) && (
                <p className="text-xs text-purple-600 flex items-center gap-1">
                  <Filter className="h-3 w-3" />
                  Le caselle con sono accessibili tramite Virtual Box
                </p>
              )}
            </>
          )}
          {errors.mailbox_id && (
            <p className="text-xs text-destructive">{errors.mailbox_id.message}</p>
          )}
        </div>

        {/* Destinatari A: */}
        <div className="space-y-1">
          <div className="flex items-center justify-between">
            <Label className="text-xs">Destinatari (A:) *</Label>
            <button
              type="button"
              onClick={() => appendTo({ value: '' })}
              className="text-xs text-primary hover:underline flex items-center gap-0.5"
            >
              <Plus className="h-3 w-3" />
              Aggiungi
            </button>
          </div>
          <div className="space-y-1.5">
            {toFields.map((field, idx) => (
              <div key={field.id} className="flex flex-col gap-0.5">
                <div className="flex gap-1.5">
                  <Input
                    type="email"
                    placeholder="destinatario@pec.it"
                    className="h-8 text-sm"
                    {...register(`to_addresses.${idx}.value`, {
                      required: idx === 0 ? 'Almeno un destinatario e obbligatorio' : false,
                      pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: 'Indirizzo non valido' },
                    })}
                  />
                  <ContactPickerPopover
                    size="sm"
                    onSelect={(email) => setValue(`to_addresses.${idx}.value`, email)}
                  />
                  {toFields.length > 1 && (
                    <button
                      type="button"
                      onClick={() => removeTo(idx)}
                      className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-destructive"
                    >
                      <X className="h-3.5 w-3.5" />
                    </button>
                  )}
                </div>
                {errors.to_addresses?.[idx]?.value && (
                  <p className="text-xs text-destructive">{errors.to_addresses[idx]?.value?.message}</p>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* CC */}
        <div className="space-y-1">
          {!showCc ? (
            <button
              type="button"
              onClick={() => { setShowCc(true); if (ccFields.length === 0) appendCc({ value: '' }) }}
              className="text-xs text-primary hover:underline"
            >
              + Aggiungi Cc
            </button>
          ) : (
            <>
              <div className="flex items-center justify-between">
                <Label className="text-xs">Copia (Cc:)</Label>
                <button
                  type="button"
                  onClick={() => appendCc({ value: '' })}
                  className="text-xs text-primary hover:underline flex items-center gap-0.5"
                >
                  <Plus className="h-3 w-3" />
                  Aggiungi
                </button>
              </div>
              {ccFields.map((field, idx) => (
                <div key={field.id} className="flex flex-col gap-0.5">
                  <div className="flex gap-1.5">
                    <Input
                      type="email"
                      placeholder="cc@pec.it"
                      className="h-8 text-sm"
                      {...register(`cc_addresses.${idx}.value`, {
                        pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: 'Indirizzo non valido' },
                      })}
                    />
                    <ContactPickerPopover
                      size="sm"
                      onSelect={(email) => setValue(`cc_addresses.${idx}.value`, email)}
                    />
                    <button
                      type="button"
                      onClick={() => removeCc(idx)}
                      className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-destructive"
                    >
                      <X className="h-3.5 w-3.5" />
                    </button>
                  </div>
                  {errors.cc_addresses?.[idx]?.value && (
                    <p className="text-xs text-destructive">{errors.cc_addresses[idx]?.value?.message}</p>
                  )}
                </div>
              ))}
            </>
          )}
        </div>

        {/* Oggetto */}
        <div className="space-y-1">
          <Label className="text-xs">Oggetto *</Label>
          <Input
            placeholder="Oggetto della PEC"
            className="h-8 text-sm"
            {...register('subject', { required: "L'oggetto e obbligatorio" })}
          />
          {errors.subject && (
            <p className="text-xs text-destructive">{errors.subject.message}</p>
          )}
        </div>

        {/* Corpo */}
        <div className="space-y-1">
          <div className="flex items-center justify-between">
            <Label className="text-xs">Testo del messaggio</Label>
            <button
              type="button"
              onClick={() => setShowTemplatePicker((v) => !v)}
              className="flex items-center gap-1 text-xs text-primary hover:underline"
              title="Usa un template come punto di partenza"
            >
              <FileText className="h-3 w-3" />
              Usa template
              <ChevronDown
                className={`h-3 w-3 transition-transform ${showTemplatePicker ? 'rotate-180' : ''}`}
              />
            </button>
          </div>

          {/* Pannello selezione template */}
          {showTemplatePicker && (
            <div className="rounded-md border bg-background shadow-sm overflow-hidden">
              {templatesLoading ? (
                <div className="p-3 text-xs text-muted-foreground text-center">
                  Caricamento template...
                </div>
              ) : !templatesData?.items.length ? (
                <div className="p-3 text-xs text-muted-foreground text-center">
                  Nessun template disponibile. Creane uno in Amministrazione.
                </div>
              ) : (
                <div className="max-h-44 overflow-y-auto divide-y">
                  {templatesData.items.map((tpl) => (
                    <button
                      key={tpl.id}
                      type="button"
                      onClick={() => applyTemplate(tpl)}
                      className="w-full text-left px-3 py-2 hover:bg-muted/60 transition-colors"
                    >
                      <p className="text-xs font-semibold text-foreground">{tpl.name}</p>
                      {tpl.description && (
                        <p className="text-xs text-muted-foreground truncate">{tpl.description}</p>
                      )}
                      {tpl.subject && (
                        <p className="text-xs text-muted-foreground/70 italic truncate">
                          Oggetto: {tpl.subject}
                        </p>
                      )}
                    </button>
                  ))}
                </div>
              )}
            </div>
          )}

          <RichTextEditor
            value={bodyHtml}
            onChange={setBodyHtml}
            placeholder="Scrivi il testo della PEC..."
            minHeight="160px"
          />
        </div>

        {/* Allegati */}
        <div className="space-y-1.5">
          <div className="flex items-center justify-between">
            <Label className="text-xs">Allegati</Label>
            <span className="text-xs text-muted-foreground">Max 20 MB</span>
          </div>
          {attachments.length > 0 && (
            <div className="space-y-1">
              {attachments.map((file, idx) => (
                <div
                  key={`${file.name}-${file.size}-${idx}`}
                  className="flex items-center gap-2 px-2.5 py-1.5 bg-muted/50 border rounded-md"
                >
                  <Paperclip className="h-3 w-3 text-muted-foreground flex-shrink-0" />
                  <span className="text-xs flex-1 truncate font-medium" title={file.name}>{file.name}</span>
                  <span className="text-xs text-muted-foreground whitespace-nowrap">{formatFileSize(file.size)}</span>
                  <button
                    type="button"
                    className="ml-1 rounded p-0.5 text-muted-foreground hover:text-destructive"
                    onClick={() => removeAttachment(idx)}
                  >
                    <X className="h-3 w-3" />
                  </button>
                </div>
              ))}
            </div>
          )}
          <div
            className="border-2 border-dashed rounded-md p-3 flex flex-col items-center gap-1.5 cursor-pointer hover:border-primary/60 hover:bg-primary/5 transition-colors"
            onClick={() => fileInputRef.current?.click()}
            onDragOver={(e) => { e.preventDefault(); e.stopPropagation() }}
            onDrop={(e) => { e.preventDefault(); handleFileAdd(e.dataTransfer.files) }}
          >
            <Upload className="h-5 w-5 text-muted-foreground" />
            <p className="text-xs text-muted-foreground">Clicca o trascina i file qui</p>
          </div>
          <input
            ref={fileInputRef}
            type="file"
            multiple
            className="hidden"
            onChange={(e) => handleFileAdd(e.target.files)}
          />
        </div>
      </div>

      {/* Footer azioni */}
      <div className="px-4 py-3 border-t flex items-center justify-between bg-muted/30">
        <button
          type="button"
          onClick={onClose}
          className="text-sm text-muted-foreground hover:text-foreground transition-colors"
        >
          Annulla
        </button>
        <Button
          type="submit"
          size="sm"
          isLoading={sendMutation.isPending}
          disabled={activeCaselle.length === 0}
        >
          <Send className="h-3.5 w-3.5 mr-1.5" />
          Invia PEC
          {attachments.length > 0 && (
            <span className="ml-1.5 bg-primary-foreground/20 text-primary-foreground rounded-full px-1.5 text-xs font-semibold">
              +{attachments.length}
            </span>
          )}
        </Button>
      </div>
    </form>
  )
}

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

export function ComposeModal() {
  const { isOpen, mode, replyTo, forwardOf, replyAll, closeCompose, setMode } = useComposeStore()

  // Chiudi con ESC (solo quando non minimizzato)
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen && mode !== 'minimized') {
        closeCompose()
      }
    }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [isOpen, mode, closeCompose])

  if (!isOpen) return null

  const title = replyAll
    ? 'Rispondi a tutti'
    : replyTo
      ? 'Rispondi a PEC'
      : forwardOf
        ? 'Inoltra PEC'
        : 'Nuova PEC'
  const subtitle = replyTo?.subject || forwardOf?.subject || null

  const containerStyle = (() => {
    if (mode === 'fullscreen') {
      return {
        position: 'fixed' as const,
        top: '1rem',
        right: '1rem',
        bottom: '1rem',
        left: '1rem',
      }
    }
    if (mode === 'minimized') {
      return {
        position: 'fixed' as const,
        bottom: 0,
        right: '1.5rem',
        width: '320px',
        height: '48px',
      }
    }
    return {
      position: 'fixed' as const,
      bottom: 0,
      right: '1.5rem',
      width: '560px',
      height: '580px',
    }
  })()

  return (
    <div
      className="z-50 flex flex-col bg-background border shadow-2xl rounded-t-xl overflow-hidden transition-all duration-200"
      style={containerStyle}
    >
      {/* Barra del titolo */}
      <div
        className="flex items-center justify-between px-4 h-12 flex-shrink-0 bg-primary text-primary-foreground select-none cursor-pointer"
        onClick={() => {
          if (mode === 'minimized') setMode('normal')
        }}
      >
        <div className="flex flex-col min-w-0">
          <span className="text-sm font-semibold truncate leading-tight">{title}</span>
          {subtitle && mode !== 'normal' && (
            <span className="text-xs opacity-75 truncate leading-tight">{subtitle}</span>
          )}
        </div>

        <div
          className="flex items-center gap-1 ml-2 flex-shrink-0"
          onClick={(e) => e.stopPropagation()}
        >
          {/* Minimizza */}
          <button
            type="button"
            title={mode === 'minimized' ? 'Espandi' : 'Minimizza'}
            onClick={() => setMode(mode === 'minimized' ? 'normal' : 'minimized')}
            className="p-1.5 rounded hover:bg-white/20 transition-colors"
          >
            <Minus className="h-3.5 w-3.5" />
          </button>

          {/* Fullscreen / Ripristina */}
          {mode !== 'minimized' && (
            <button
              type="button"
              title={mode === 'fullscreen' ? 'Ripristina dimensione' : 'Schermo intero'}
              onClick={() => setMode(mode === 'fullscreen' ? 'normal' : 'fullscreen')}
              className="p-1.5 rounded hover:bg-white/20 transition-colors"
            >
              {mode === 'fullscreen' ? (
                <Minimize2 className="h-3.5 w-3.5" />
              ) : (
                <Maximize2 className="h-3.5 w-3.5" />
              )}
            </button>
          )}

          {/* Chiudi */}
          <button
            type="button"
            title="Chiudi"
            onClick={closeCompose}
            className="p-1.5 rounded hover:bg-white/20 transition-colors"
          >
            <X className="h-3.5 w-3.5" />
          </button>
        </div>
      </div>

      {/* Corpo (nascosto quando minimizzato) */}
      {mode !== 'minimized' && (
        <div className="flex-1 overflow-hidden flex flex-col">
          {/*
            Key basata su replyTo/forwardOf/replyAll: garantisce che il form venga rimontato
            ogni volta che si apre per un messaggio diverso o cambia la modalita'.
          */}
          <ComposeForm
            key={`${replyTo?.id ?? 'new'}-${forwardOf?.id ?? 'new'}-${replyAll ? 'all' : 'single'}`}
            replyTo={replyTo}
            forwardOf={forwardOf}
            replyAll={replyAll}
            onClose={closeCompose}
          />
        </div>
      )}
    </div>
  )
}
