import { useState, useRef, useMemo, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useForm, useFieldArray, useWatch } from 'react-hook-form'
import { Send, X, Plus, ArrowLeft, AlertCircle, Paperclip, Upload, Filter, FileText, ChevronDown } from 'lucide-react'
import { ContactPickerPopover } from '@/components/ComposeModal/ContactPickerPopover'
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 { 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 type { MessageResponse } from '@/types/api.types'

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

const SIG_ATTR = 'data-pechub-sig'

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>')
  }
  return withoutSig + sigBlock
}

/** Tipo unificato casella mittente (sia da permessi diretti che da Virtual Box) */
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
}

const MAX_FILE_SIZE = 20 * 1024 * 1024 // 20 MB

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`
}

/** Estrae testo semplice dall'HTML del rich editor per la parte text/plain dell'email */
function htmlToText(html: string): string {
  if (!html || html === '<p></p>') return ''
  const div = document.createElement('div')
  div.innerHTML = html
  return div.textContent || div.innerText || ''
}

export function ComposePage() {
  const navigate = useNavigate()
  const location = useLocation()
  const replyTo = location.state?.replyTo as MessageResponse | undefined
  const forwardOf = location.state?.forwardOf as MessageResponse | undefined
  const [showCc, setShowCc] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  // Corpo HTML (gestito da TipTap)
  const [bodyHtml, setBodyHtml] = useState<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 ''
  })

  // Allegati
  const [attachments, setAttachments] = useState<File[]>([])

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

  const {
    fields: toFields,
    append: appendTo,
    remove: removeTo,
  } = 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'
  // Ref per tenere traccia dell'HTML firma corrente (usato da applyTemplate)
  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) => {
    // Preserva la parte citata (tutto dal separatore <hr> in poi)
    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))
    // Applica oggetto solo su nuova PEC (non su risposta/inoltro)
    if (!replyTo && !forwardOf && tpl.subject) {
      setValue('subject', tpl.subject)
    }
    setShowTemplatePicker(false)
    toast.success(`Template "${tpl.name}" applicato`)
  }
  // ─────────────────────────────────────────────────────────────────────────

  // Carica caselle disponibili per l'invio (permessi diretti)
  const { data: mailboxesData, isLoading: mailboxesLoading } = useQuery({
    queryKey: ['mailboxes'],
    queryFn: () => mailboxesApi.list(),
  })

  // Carica caselle disponibili tramite Virtual Box (operatori senza permessi diretti)
  const { data: vboxMailboxes = [], isLoading: vboxMailboxesLoading } = useQuery({
    queryKey: ['virtual-boxes', 'my-mailboxes'],
    queryFn: () => virtualBoxesApi.getMyMailboxes(),
  })

  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)}...`)
      navigate('/sent')
    },
    onError: (error) => {
      toast.error(getErrorMessage(error))
    },
  })

  // ── Gestione allegati ──────────────────────────────────────────────────────

  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))
  }

  // ── Submit ─────────────────────────────────────────────────────────────────

  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,
    })
  }

  // ── Lista unificata caselle mittente ──────────────────────────────────────
  // Combina caselle con permesso diretto + caselle accessibili via VBox
  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))

    // Aggiungi caselle VBox non già presenti nella lista diretta
    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

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="border-b bg-background px-6 py-4 flex items-center gap-3">
        <Button variant="ghost" size="icon" onClick={() => navigate(-1)}>
          <ArrowLeft className="h-5 w-5" />
        </Button>
        <div>
          <h1 className="text-lg font-semibold">
            {replyTo ? 'Rispondi a PEC' : forwardOf ? 'Inoltra PEC' : 'Nuova PEC'}
          </h1>
          {replyTo && (
            <p className="text-xs text-muted-foreground">
              In risposta a: {replyTo.subject}
            </p>
          )}
          {forwardOf && (
            <p className="text-xs text-muted-foreground">
              Inoltro di: {forwardOf.subject}
            </p>
          )}
        </div>
      </div>

      {/* Form */}
      <div className="flex-1 overflow-y-auto">
        <form
          onSubmit={handleSubmit(onSubmit)}
          noValidate
          className="max-w-4xl mx-auto px-6 py-6 space-y-5"
        >
          {/* Avviso informativo */}
          <div className="rounded-lg border border-blue-200 bg-blue-50 p-3 flex items-start gap-2">
            <AlertCircle className="h-4 w-4 text-blue-600 mt-0.5 flex-shrink-0" />
            <p className="text-sm text-blue-700">
              L'invio avviene tramite il server PEC della casella selezionata.
              La ricevuta di accettazione arriverà entro pochi minuti.
            </p>
          </div>

          {/* Avviso allegati messaggio inoltrato */}
          {forwardOf && forwardOf.has_attachments && (
            <div className="rounded-lg border border-amber-200 bg-amber-50 p-3 flex items-start gap-2">
              <Paperclip className="h-4 w-4 text-amber-600 mt-0.5 flex-shrink-0" />
              <p className="text-sm text-amber-700">
                Il messaggio originale contiene allegati. Per includerli nell'inoltro,
                scaricali dal messaggio originale e aggiungili qui manualmente.
              </p>
            </div>
          )}

          {/* Casella mittente */}
          <div className="space-y-1.5">
            <Label htmlFor="mailbox_id">Casella mittente *</Label>
            {isLoadingMailboxes ? (
              <div className="h-10 rounded-md border bg-muted animate-pulse" />
            ) : activeCaselle.length === 0 ? (
              <div className="rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive">
                Nessuna casella PEC attiva disponibile. Contatta l'amministratore.
              </div>
            ) : (
              <>
                <select
                  id="mailbox_id"
                  className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                  {...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.5">
            <div className="flex items-center justify-between">
              <Label>Destinatari (A:) *</Label>
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => appendTo({ value: '' })}
              >
                <Plus className="h-4 w-4 mr-1" />
                Aggiungi
              </Button>
            </div>
            <div className="space-y-2">
              {toFields.map((field, idx) => (
                <div key={field.id} className="flex flex-col gap-1">
                  <div className="flex gap-2">
                    <Input
                      type="email"
                      placeholder="destinatario@pec.it"
                      {...register(`to_addresses.${idx}.value`, {
                        required:
                          idx === 0 ? 'Almeno un destinatario è obbligatorio' : false,
                        pattern: {
                          value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
                          message: 'Inserisci un indirizzo email valido',
                        },
                      })}
                    />
                    <ContactPickerPopover
                      size="md"
                      onSelect={(email) => setValue(`to_addresses.${idx}.value`, email)}
                    />
                    {toFields.length > 1 && (
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        onClick={() => removeTo(idx)}
                      >
                        <X className="h-4 w-4" />
                      </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.5">
            {!showCc ? (
              <button
                type="button"
                onClick={() => setShowCc(true)}
                className="text-sm text-primary hover:underline"
              >
                + Aggiungi Cc
              </button>
            ) : (
              <>
                <div className="flex items-center justify-between">
                  <Label>Copia (Cc:)</Label>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => appendCc({ value: '' })}
                  >
                    <Plus className="h-4 w-4 mr-1" />
                    Aggiungi
                  </Button>
                </div>
                {ccFields.map((field, idx) => (
                  <div key={field.id} className="flex flex-col gap-1">
                    <div className="flex gap-2">
                      <Input
                        type="email"
                        placeholder="cc@pec.it"
                        {...register(`cc_addresses.${idx}.value`, {
                          pattern: {
                            value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
                            message: 'Inserisci un indirizzo email valido',
                          },
                        })}
                      />
                      <ContactPickerPopover
                        size="md"
                        onSelect={(email) => setValue(`cc_addresses.${idx}.value`, email)}
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        onClick={() => removeCc(idx)}
                      >
                        <X className="h-4 w-4" />
                      </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.5">
            <Label htmlFor="subject">Oggetto *</Label>
            <Input
              id="subject"
              placeholder="Oggetto della PEC"
              {...register('subject', { required: "L'oggetto è obbligatorio" })}
            />
            {errors.subject && (
              <p className="text-xs text-destructive">{errors.subject.message}</p>
            )}
          </div>

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

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

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

          {/* ── Allegati ────────────────────────────────────────────────── */}
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <Label>Allegati</Label>
              <span className="text-xs text-muted-foreground">Max 20 MB per file</span>
            </div>

            {/* Lista allegati caricati */}
            {attachments.length > 0 && (
              <div className="space-y-1.5">
                {attachments.map((file, idx) => (
                  <div
                    key={`${file.name}-${file.size}-${idx}`}
                    className="flex items-center gap-2.5 px-3 py-2 bg-muted/50 border rounded-md"
                  >
                    <Paperclip className="h-3.5 w-3.5 text-muted-foreground flex-shrink-0" />
                    <span
                      className="text-sm 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 hover:bg-destructive/10 transition-colors"
                      onClick={() => removeAttachment(idx)}
                      title="Rimuovi allegato"
                    >
                      <X className="h-3.5 w-3.5" />
                    </button>
                  </div>
                ))}
              </div>
            )}

            {/* Zona drag-and-drop / click per aggiungere file */}
            <div
              className="border-2 border-dashed rounded-md p-5 flex flex-col items-center gap-2 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-7 w-7 text-muted-foreground" />
              <div className="text-center">
                <p className="text-sm font-medium text-foreground">
                  Clicca o trascina i file qui
                </p>
                <p className="text-xs text-muted-foreground mt-0.5">
                  Qualsiasi tipo di file • Max 20 MB per file
                </p>
              </div>
            </div>

            {/* Input file nascosto */}
            <input
              ref={fileInputRef}
              type="file"
              multiple
              className="hidden"
              onChange={(e) => handleFileAdd(e.target.files)}
            />
          </div>

          {/* ── Azioni ──────────────────────────────────────────────────── */}
          <div className="flex items-center justify-between pt-4 border-t">
            <Button type="button" variant="outline" onClick={() => navigate(-1)}>
              Annulla
            </Button>
            <Button
              type="submit"
              isLoading={sendMutation.isPending}
              disabled={activeCaselle.length === 0}
            >
              <Send className="h-4 w-4 mr-2" />
              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>
      </div>
    </div>
  )
}
