"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { AlertCircle, Loader2, CheckCircle2 } from "lucide-react";

export function CancelSubscriptionButton({
  isPremium,
  subscriptionEndDate,
  isScheduledForCancellation,
}: {
  isPremium: boolean;
  subscriptionEndDate?: Date;
  isScheduledForCancellation?: boolean;
}) {
  const router = useRouter();
  const [canceling, setCanceling] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showConfirm, setShowConfirm] = useState(false);
  const [isCanceled, setIsCanceled] = useState(!!isScheduledForCancellation);

  if (!isPremium) return null;

  async function handleCancel() {
    setCanceling(true);
    setError(null);

    try {
      const res = await fetch("/api/stripe/cancel-subscription", {
        method: "POST",
      });

      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error ?? "Erreur lors de la résiliation.");
      }

      setShowConfirm(false);
      setIsCanceled(true);
      router.refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Erreur inconnue");
    } finally {
      setCanceling(false);
    }
  }

  const endDateFormatted = subscriptionEndDate
    ? new Intl.DateTimeFormat("fr-FR", {
        year: "numeric",
        month: "long",
        day: "numeric",
      }).format(subscriptionEndDate)
    : null;

  return (
    <div className="space-y-3">
      {isCanceled ? (
        <div className="rounded-lg border border-emerald-300 bg-emerald-50 p-4 space-y-2">
          <div className="flex gap-2">
            <CheckCircle2 className="h-5 w-5 flex-shrink-0 text-emerald-600" />
            <div className="text-sm text-emerald-800">
              <p className="font-medium">Abonnement résilié</p>
              <p className="text-emerald-700">
                Votre accès Premium reste actif jusqu'au {endDateFormatted}.
              </p>
            </div>
          </div>
        </div>
      ) : !showConfirm ? (
        <button
          type="button"
          onClick={() => setShowConfirm(true)}
          className="w-full rounded-lg border border-rose-300 bg-rose-50 px-4 py-3 text-sm font-medium text-rose-700 hover:bg-rose-100"
        >
          Résilier mon abonnement Premium
        </button>
      ) : (
        <div className="rounded-lg border border-rose-300 bg-rose-50 p-4 space-y-3">
          <div className="flex gap-2">
            <AlertCircle className="h-5 w-5 flex-shrink-0 text-rose-600" />
            <div className="text-sm text-rose-800">
              <p className="font-medium mb-1">Êtes-vous sûr ?</p>
              <p className="text-rose-700">
                Votre accès Premium restera actif jusqu'au {endDateFormatted}. Après cette date, vous reviendrez au plan gratuit.
              </p>
            </div>
          </div>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => setShowConfirm(false)}
              disabled={canceling}
              className="flex-1 rounded-lg border border-rose-300 bg-white px-3 py-2 text-sm font-medium text-rose-700 hover:bg-rose-50 disabled:opacity-60"
            >
              Annuler
            </button>
            <button
              type="button"
              onClick={handleCancel}
              disabled={canceling}
              className="flex-1 inline-flex items-center justify-center gap-2 rounded-lg bg-rose-600 px-3 py-2 text-sm font-medium text-white hover:bg-rose-700 disabled:opacity-60"
            >
              {canceling ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
              Confirmer la résiliation
            </button>
          </div>
        </div>
      )}
      {error && (
        <div className="rounded-md border border-rose-300 bg-rose-50 px-3 py-2 text-sm text-rose-800">
          {error}
        </div>
      )}
    </div>
  );
}
