import { useState } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useForm, useFieldArray } from 'react-hook-form'
import { Send, X, Plus, ArrowLeft, AlertCircle } 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 { sendApi } from '@/api/send.api'
import { mailboxesApi } from '@/api/mailboxes.api'
import { getErrorMessage } from '@/api/client'
import type { MessageResponse } from '@/types/api.types'

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

export function ComposePage() {
  const navigate = useNavigate()
  const location = useLocation()
  const replyTo = location.state?.replyTo as MessageResponse | undefined
  const [showCc, setShowCc] = useState(false)

  const {
    register,
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<ComposeFormValues>({
    defaultValues: {
      mailbox_id: replyTo?.mailbox_id || '',
      to_addresses: replyTo ? [{ value: replyTo.from_address || '' }] : [{ value: '' }],
      cc_addresses: [],
      subject: replyTo ? `Re: ${replyTo.subject || ''}` : '',
      body_text: replyTo
        ? `\n\n---\nIn risposta al messaggio del ${new Date(replyTo.received_at || replyTo.created_at).toLocaleDateString('it-IT')}\nDa: ${replyTo.from_address || ''}\nA: ${replyTo.to_addresses?.join(', ') || ''}\nOggetto: ${replyTo.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' })

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

  const sendMutation = useMutation({
    mutationFn: sendApi.send,
    onSuccess: (job) => {
      toast.success(`PEC inviata! Job ID: ${job.id.slice(0, 8)}...`)
      navigate('/sent')
    },
    onError: (error) => {
      toast.error(getErrorMessage(error))
    },
  })

  const onSubmit = async (data: ComposeFormValues) => {
    const toAddresses = data.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({
      mailbox_id: data.mailbox_id,
      to_addresses: toAddresses,
      cc_addresses: data.cc_addresses
        .map((c) => c.value.trim())
        .filter((v) => v.length > 0),
      subject: data.subject,
      body_text: data.body_text,
      reply_to_message_id: replyTo?.id,
    })
  }

  const activeCaselle = mailboxesData?.items.filter((m) => m.status === 'active') || []

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="border-b bg-background px-6 py-4 flex items-center justify-between">
        <div className="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' : 'Nuova PEC'}
            </h1>
            {replyTo && (
              <p className="text-xs text-muted-foreground">
                In risposta a: {replyTo.subject}
              </p>
            )}
          </div>
        </div>
      </div>

      {/* Form */}
      <div className="flex-1 overflow-y-auto">
        <form onSubmit={handleSubmit(onSubmit)} className="max-w-3xl mx-auto px-6 py-8 space-y-6">
          {/* Avviso */}
          <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>

          {/* Casella mittente */}
          <div className="space-y-2">
            <Label htmlFor="mailbox_id">Casella mittente *</Label>
            {mailboxesLoading ? (
              <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"
                {...register('mailbox_id', { required: 'Seleziona una casella mittente' })}
              >
                <option value="">Seleziona casella...</option>
                {activeCaselle.map((mb) => (
                  <option key={mb.id} value={mb.id}>
                    {mb.display_name || mb.email_address} ({mb.email_address})
                  </option>
                ))}
              </select>
            )}
            {errors.mailbox_id && (
              <p className="text-xs text-destructive">{errors.mailbox_id.message}</p>
            )}
          </div>

          {/* Destinatari A: */}
          <div className="space-y-2">
            <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 gap-2">
                  <Input
                    type="email"
                    placeholder="destinatario@pec.it"
                    {...register(`to_addresses.${idx}.value`, {
                      required: idx === 0 ? 'Almeno un destinatario è obbligatorio' : false,
                    })}
                  />
                  {toFields.length > 1 && (
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      onClick={() => removeTo(idx)}
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  )}
                </div>
              ))}
            </div>
            {errors.to_addresses?.[0]?.value && (
              <p className="text-xs text-destructive">
                {errors.to_addresses[0].value.message}
              </p>
            )}
          </div>

          {/* CC */}
          <div className="space-y-2">
            {!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 gap-2">
                    <Input
                      type="email"
                      placeholder="cc@pec.it"
                      {...register(`cc_addresses.${idx}.value`)}
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      onClick={() => removeCc(idx)}
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                ))}
              </>
            )}
          </div>

          {/* Oggetto */}
          <div className="space-y-2">
            <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 */}
          <div className="space-y-2">
            <Label htmlFor="body_text">Testo del messaggio</Label>
            <textarea
              id="body_text"
              rows={12}
              placeholder="Testo della PEC..."
              className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 resize-y"
              {...register('body_text')}
            />
          </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
            </Button>
          </div>
        </form>
      </div>
    </div>
  )
}
