"use client";

import { useEffect, useState } from "react";
import { RefreshCw } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogTitle,
} from "@/components/ui/dialog";
import { Panel, PreviewNotice, StatusBadge } from "@/components/shared/page";
import {
  cancelSubscription,
  getCurrentSubscription,
  type CurrentSubscription,
} from "./subscription-api";

type LoadState = "loading" | "loaded" | "failed";

export function SubscriptionCancellation({
  editable,
  initialSubscriptionId = "",
}: {
  editable: boolean;
  initialSubscriptionId?: string;
}) {
  const [subscription, setSubscription] = useState<CurrentSubscription | null>(
    () =>
      initialSubscriptionId
        ? { id: initialSubscriptionId, status: "pending_payment" }
        : null,
  );
  const [loadState, setLoadState] = useState<LoadState>("loading");
  const [reloadKey, setReloadKey] = useState(0);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");

  useEffect(() => {
    const controller = new AbortController();
    setLoadState("loading");
    void getCurrentSubscription(controller.signal)
      .then((current) => {
        if (controller.signal.aborted) return;
        setSubscription(current);
        setLoadState("loaded");
        setError("");
      })
      .catch((loadError: unknown) => {
        if (controller.signal.aborted) return;
        setLoadState("failed");
        setError(
          loadError instanceof Error
            ? loadError.message
            : "Could not load the current subscription.",
        );
      });
    return () => controller.abort();
  }, [reloadKey]);

  async function submit() {
    if (!editable || !subscription || subscription.status !== "active") return;
    setError("");
    setNotice("");
    setBusy(true);
    try {
      await cancelSubscription(subscription.id);
      setSubscription({ ...subscription, status: "cancelled" });
      setDialogOpen(false);
      setNotice("Monet confirmed the subscription cancellation.");
    } catch (cancelError: unknown) {
      setError(
        cancelError instanceof Error
          ? cancelError.message
          : "Could not cancel the subscription.",
      );
    } finally {
      setBusy(false);
    }
  }

  if (loadState === "loading") {
    return (
      <Panel title="Subscription">
        <p className="p-5 text-sm text-muted-foreground">
          Checking current subscription…
        </p>
      </Panel>
    );
  }

  if (loadState === "failed") {
    return (
      <>
        <Panel title="Subscription status unavailable">
          <div className="flex flex-wrap items-center justify-between gap-4 p-5">
            <p role="alert" className="text-sm text-destructive">
              {error}
            </p>
            <Button
              variant="outline"
              onClick={() => {
                setError("");
                setLoadState("loading");
                setReloadKey((current) => current + 1);
              }}
            >
              Try again
            </Button>
          </div>
        </Panel>
        {notice && <PreviewNotice>{notice}</PreviewNotice>}
      </>
    );
  }

  if (!subscription) {
    return notice ? <PreviewNotice>{notice}</PreviewNotice> : null;
  }

  return (
    <>
      <Panel
        title="Current subscription"
        description={
          subscription.status === "active"
            ? "Current subscription details for this tenant."
            : subscription.status === "pending_payment"
              ? "The setup invoice is pending and will be handled by an admin."
              : undefined
        }
      >
        <div className="flex flex-wrap items-center justify-between gap-4 p-5">
          <div className="space-y-2">
            <div className="flex items-center gap-3 text-sm">
              <span className="text-muted-foreground">Status</span>
              <StatusBadge>{subscription.status.replaceAll("_", " ")}</StatusBadge>
            </div>
            <p className="text-sm text-muted-foreground">
              Contract ID: <span className="font-mono">{subscription.id}</span>
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            <Button
              variant="outline"
              disabled={busy}
              onClick={() => setReloadKey((current) => current + 1)}
            >
              <RefreshCw size={16} />
              Refresh status
            </Button>
            {subscription.status === "active" && (
              <Button
                variant="destructive"
                disabled={!editable || busy}
                onClick={() => setDialogOpen(true)}
              >
                Cancel subscription
              </Button>
            )}
          </div>
        </div>
      </Panel>
      {notice && <PreviewNotice>{notice}</PreviewNotice>}
      {error && (
        <p role="alert" className="text-sm text-destructive">
          {error}
        </p>
      )}

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent>
          <DialogTitle>Cancel this subscription?</DialogTitle>
          <DialogDescription>
            Monet will cancel this tenant&apos;s current subscription. This
            cannot be undone from this screen.
          </DialogDescription>
          <DialogFooter>
            <Button
              variant="outline"
              disabled={busy}
              onClick={() => setDialogOpen(false)}
            >
              Keep subscription
            </Button>
            <Button
              variant="destructive"
              disabled={busy || !subscription}
              onClick={() => void submit()}
            >
              {busy ? "Cancelling…" : "Confirm cancellation"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
