"use client"

import { useState } from "react"
import { Loader2 } from "lucide-react"
import { useListUnsubscribeMailto } from "@/lib/api/hooks/use-list-unsubscribe-mailto"
import type { UnsubscribeAction } from "@/lib/mail-unsubscribe"

export function UnsubscribeActionButton({
  action,
  messageId,
}: {
  action: UnsubscribeAction
  messageId: string
}) {
  const sendMailto = useListUnsubscribeMailto()
  const [done, setDone] = useState(false)
  const [error, setError] = useState<string | null>(null)

  if (action.kind === "http") {
    return (
      <a
        href={action.url}
        target="_blank"
        rel="noopener noreferrer"
        className="text-primary hover:underline"
      >
        Se désabonner de cet expéditeur
      </a>
    )
  }

  const handleClick = async () => {
    setError(null)
    try {
      await sendMailto.mutateAsync(messageId)
      setDone(true)
    } catch (e) {
      setError(e instanceof Error ? e.message : "Échec de l’envoi")
    }
  }

  if (done) {
    return (
      <span className="text-muted-foreground">
        Demande de désinscription envoyée à {action.mailto.address}
      </span>
    )
  }

  return (
    <span className="inline-flex flex-col gap-1">
      <button
        type="button"
        onClick={() => void handleClick()}
        disabled={sendMailto.isPending}
        className="text-left text-primary hover:underline disabled:opacity-60"
      >
        {sendMailto.isPending ? (
          <span className="inline-flex items-center gap-1.5">
            <Loader2 className="size-3.5 animate-spin" />
            Envoi…
          </span>
        ) : (
          "Se désabonner de cet expéditeur"
        )}
      </button>
      {error ? <span className="text-destructive">{error}</span> : null}
    </span>
  )
}
