"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";

interface Props {
  tenantName: string;
  /**
   * Current suspend state — server-derived. The control toggles this
   * via PATCH /api/tenants/[name]/suspend, then refreshes the route
   * so server-component-side data (status badge, suspended notice)
   * re-renders.
   */
  suspended: boolean;
}

/**
 * SubscriptionToggle — owner-side cancel/resume control (Bug 31).
 *
 * Renders a single button that toggles between "Cancel subscription"
 * (when active) and "Resume subscription" (when suspended). Cancellation
 * is gated behind a confirmation modal because it's destructive
 * looking from the user's POV — even though no data is lost, the
 * AI assistant becomes unavailable until they resume. Resume has no
 * modal; it's a strict subset of cancellation in terms of risk.
 *
 * The control intentionally lives at the bottom of the tenant detail
 * page rather than next to the status badge — putting it near the
 * top would invite mis-clicks. Customers who want to cancel scroll
 * past the running configuration, billing-relevant info, and assigned
 * users first; that's the right friction level.
 *
 * Suspended tenants render a top-of-page banner separately (see the
 * detail page); this component focuses on the action itself.
 */
export function SubscriptionToggle({ tenantName, suspended }: Props) {
  const t = useTranslations("tenantDetail");
  const tCommon = useTranslations("common");
  const router = useRouter();

  const [confirmOpen, setConfirmOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  const toggleSuspend = async (next: boolean) => {
    setSubmitting(true);
    setError("");
    try {
      const res = await fetch(
        `/api/tenants/${encodeURIComponent(tenantName)}/suspend`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ suspend: next }),
        }
      );
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || t("subscriptionUpdateFailed"));
      }
      setConfirmOpen(false);
      // The status badge + suspended banner are server-rendered, so
      // a route refresh is the simplest way to reflect the new state.
      // Optimistic local toggle would diverge from the actual CR if
      // the operator hasn't observed the patch yet.
      router.refresh();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setSubmitting(false);
    }
  };

  if (suspended) {
    return (
      <div>
        <button
          type="button"
          onClick={() => toggleSuspend(false)}
          disabled={submitting}
          className="text-sm font-medium px-4 py-2 rounded-lg border border-success/30 text-success hover:bg-success/10 transition-colors disabled:opacity-50"
        >
          {submitting ? tCommon("loading") : t("resumeSubscription")}
        </button>
        {error && <p className="text-xs text-red-400 mt-2">{error}</p>}
      </div>
    );
  }

  return (
    <div>
      <button
        type="button"
        onClick={() => setConfirmOpen(true)}
        className="text-sm font-medium px-4 py-2 rounded-lg border border-border text-text-secondary hover:text-text-primary hover:border-text-secondary transition-colors"
      >
        {t("cancelSubscription")}
      </button>
      {error && !confirmOpen && (
        <p className="text-xs text-red-400 mt-2">{error}</p>
      )}

      {confirmOpen && (
        <div
          role="dialog"
          aria-modal="true"
          className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm"
          onClick={(e) => {
            if (e.target === e.currentTarget) setConfirmOpen(false);
          }}
        >
          <div className="bg-surface-1 border border-border rounded-xl p-6 max-w-md w-full">
            <h3 className="font-display text-lg font-semibold text-text-primary mb-2">
              {t("cancelConfirmTitle")}
            </h3>
            <p className="text-sm text-text-secondary mb-3">
              {t("cancelConfirmDescription")}
            </p>
            <ul className="text-xs text-text-muted list-disc list-inside space-y-1 mb-5">
              <li>{t("cancelConfirmBullet1")}</li>
              <li>{t("cancelConfirmBullet2")}</li>
              <li>{t("cancelConfirmBullet3")}</li>
            </ul>

            {error && (
              <div className="text-xs text-red-400 bg-red-400/10 border border-red-400/20 rounded-lg px-3 py-2 mb-3">
                {error}
              </div>
            )}

            <div className="flex justify-end gap-2">
              <button
                type="button"
                onClick={() => setConfirmOpen(false)}
                disabled={submitting}
                className="text-sm px-4 py-2 rounded-lg border border-border text-text-secondary hover:text-text-primary transition-colors"
              >
                {tCommon("cancel")}
              </button>
              <button
                type="button"
                onClick={() => toggleSuspend(true)}
                disabled={submitting}
                className="text-sm px-4 py-2 rounded-lg bg-amber-500 text-white hover:bg-amber-600 transition-colors disabled:opacity-50"
              >
                {submitting
                  ? tCommon("loading")
                  : t("cancelSubscriptionConfirm")}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
