// src/components/admin/org-billing-panel.tsx — God-Mode Stripe supervision panel
// (client). Wires the four Slice-4 actions for one org: Resync (force a failed
// webhook), Extend trial, Apply coupon, Grant complimentary. The two Stripe-API
// actions (Resync, Apply coupon) are disabled + explained when Stripe isn't
// configured; the impactful ones sit behind AlertDialog confirmations. Every
// button calls a 2FA-gated + audited server action and refreshes the RSC tree.
"use client";

import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { useState, useTransition } from "react";
import { toast } from "sonner";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import {
  applyCouponAction,
  extendOrgTrialAction,
  grantComplimentaryAction,
  resyncOrgSubscriptionAction,
} from "@/lib/admin/billing-actions";
import type { OrgBillingDetail } from "@/lib/admin/billing-queries";

const PLANS = ["solo", "starter", "pro", "agency"] as const;

export function OrgBillingPanel({ billing }: { billing: OrgBillingDetail }) {
  const t = useTranslations("SuperAdmin");
  const router = useRouter();
  const [pending, startTransition] = useTransition();

  // Extend-trial form.
  const [trialDays, setTrialDays] = useState("14");
  // Apply-coupon form.
  const [couponId, setCouponId] = useState("");
  // Grant-complimentary form.
  const [compPlan, setCompPlan] = useState<string>("none");
  const [compUntil, setCompUntil] = useState("");
  const [compNote, setCompNote] = useState("");

  const stripeOff = !billing.stripeConfigured;
  const canResync = billing.stripeConfigured && Boolean(billing.subscription);
  const canCoupon =
    billing.stripeConfigured &&
    (billing.hasActiveSubscription || Boolean(billing.stripeCustomerId));

  function run(action: () => Promise<void>, okMsg: string) {
    startTransition(async () => {
      try {
        await action();
        toast.success(okMsg);
        router.refresh();
      } catch (err) {
        toast.error(err instanceof Error ? err.message : t("actionError"));
      }
    });
  }

  return (
    <section className="space-y-4 rounded-lg border p-4">
      <div className="flex flex-wrap items-center gap-2">
        <h2 className="font-semibold text-lg">{t("billingPanelTitle")}</h2>
        {stripeOff ? (
          <Badge variant="destructive">{t("billingStripeOff")}</Badge>
        ) : null}
      </div>
      <p className="text-muted-foreground text-sm">{t("billingPanelBody")}</p>

      <div className="flex flex-wrap gap-2">
        {/* Resync (Stripe API) */}
        <AlertDialog>
          <AlertDialogTrigger asChild>
            <Button
              variant="outline"
              size="sm"
              disabled={pending || !canResync}
            >
              {t("billingResync")}
            </Button>
          </AlertDialogTrigger>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>{t("billingResyncTitle")}</AlertDialogTitle>
              <AlertDialogDescription>
                {t("billingResyncBody")}
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>{t("cancel")}</AlertDialogCancel>
              <AlertDialogAction
                onClick={() =>
                  run(
                    () => resyncOrgSubscriptionAction(billing.orgId),
                    t("billingResyncOk"),
                  )
                }
              >
                {t("billingResync")}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>

        {/* Extend trial (app-level) */}
        <Dialog>
          <DialogTrigger asChild>
            <Button variant="secondary" size="sm" disabled={pending}>
              {t("billingExtendTrial")}
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{t("billingExtendTitle")}</DialogTitle>
              <DialogDescription>{t("billingExtendBody")}</DialogDescription>
            </DialogHeader>
            <div className="space-y-2">
              <Label htmlFor="trial-days">{t("billingExtendDays")}</Label>
              <Input
                id="trial-days"
                inputMode="numeric"
                value={trialDays}
                onChange={(e) => setTrialDays(e.target.value)}
              />
            </div>
            <DialogFooter>
              <DialogClose asChild>
                <Button variant="ghost">{t("cancel")}</Button>
              </DialogClose>
              <DialogClose asChild>
                <Button
                  disabled={pending}
                  onClick={() =>
                    run(
                      () =>
                        extendOrgTrialAction(billing.orgId, {
                          days: Number.parseInt(trialDays, 10) || 0,
                        }),
                      t("billingExtendOk"),
                    )
                  }
                >
                  {t("save")}
                </Button>
              </DialogClose>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Apply coupon (Stripe API) */}
        <Dialog>
          <DialogTrigger asChild>
            <Button
              variant="secondary"
              size="sm"
              disabled={pending || !canCoupon}
            >
              {t("billingApplyCoupon")}
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{t("billingCouponTitle")}</DialogTitle>
              <DialogDescription>{t("billingCouponBody")}</DialogDescription>
            </DialogHeader>
            <div className="space-y-2">
              <Label htmlFor="coupon-id">{t("billingCouponId")}</Label>
              <Input
                id="coupon-id"
                value={couponId}
                onChange={(e) => setCouponId(e.target.value)}
                placeholder="LAUNCH50"
              />
            </div>
            <DialogFooter>
              <DialogClose asChild>
                <Button variant="ghost">{t("cancel")}</Button>
              </DialogClose>
              <DialogClose asChild>
                <Button
                  disabled={pending || couponId.trim() === ""}
                  onClick={() =>
                    run(
                      () => applyCouponAction(billing.orgId, couponId.trim()),
                      t("billingCouponOk"),
                    )
                  }
                >
                  {t("save")}
                </Button>
              </DialogClose>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Grant complimentary (app-level, no Stripe) */}
        <Dialog>
          <DialogTrigger asChild>
            <Button variant="secondary" size="sm" disabled={pending}>
              {t("billingGrantComp")}
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{t("billingCompTitle")}</DialogTitle>
              <DialogDescription>{t("billingCompBody")}</DialogDescription>
            </DialogHeader>
            <div className="space-y-3">
              <div className="space-y-1">
                <Label htmlFor="comp-plan">{t("billingCompPlan")}</Label>
                <Select value={compPlan} onValueChange={setCompPlan}>
                  <SelectTrigger id="comp-plan">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent position="popper">
                    <SelectItem value="none">
                      {t("billingCompPlanNone")}
                    </SelectItem>
                    {PLANS.map((p) => (
                      <SelectItem key={p} value={p}>
                        {p}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1">
                <Label htmlFor="comp-until">{t("billingCompUntil")}</Label>
                <Input
                  id="comp-until"
                  type="date"
                  value={compUntil}
                  onChange={(e) => setCompUntil(e.target.value)}
                />
              </div>
              <div className="space-y-1">
                <Label htmlFor="comp-note">{t("billingCompNote")}</Label>
                <Textarea
                  id="comp-note"
                  value={compNote}
                  onChange={(e) => setCompNote(e.target.value)}
                  placeholder={t("billingCompNotePlaceholder")}
                />
              </div>
            </div>
            <DialogFooter>
              <DialogClose asChild>
                <Button variant="ghost">{t("cancel")}</Button>
              </DialogClose>
              <DialogClose asChild>
                <Button
                  disabled={
                    pending || compUntil === "" || compNote.trim() === ""
                  }
                  onClick={() =>
                    run(
                      () =>
                        grantComplimentaryAction(billing.orgId, {
                          plan:
                            compPlan === "none"
                              ? undefined
                              : (compPlan as (typeof PLANS)[number]),
                          until: new Date(compUntil),
                          note: compNote.trim(),
                        }),
                      t("billingCompOk"),
                    )
                  }
                >
                  {t("save")}
                </Button>
              </DialogClose>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>
    </section>
  );
}
