import { useEffect, useMemo, useState } from "react" import { ChevronDown, Gift, Search } from "lucide-react" import { toast } from "sonner" import { adminApplySubscription } from "../../../api/admin-subscriptions.api" import { getSubscriptionPlans } from "../../../api/subscription-plans.api" import { Button } from "../../../components/ui/button" import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "../../../components/ui/dialog" import { Input } from "../../../components/ui/input" import { SpinnerIcon } from "../../../components/ui/spinner-icon" import { getApiErrorMessage, notifyApiError } from "../../../lib/apiErrors" import { formatPlanCategory, formatPlanDuration, formatPlanPrice, } from "../../../lib/subscriptionPlans" import { TypeToConfirmDialog } from "../../../lib/typeToConfirm" import { cn } from "../../../lib/utils" import type { SubscriptionPlan } from "../../../types/subscription.types" const CONFIRM_WORD = "GRANT" type GrantSubscriptionDialogProps = { open: boolean onOpenChange: (open: boolean) => void userId: number userName?: string activeByCategory: Record onGranted: () => void } function planLabel(plan: SubscriptionPlan): string { return `${plan.name} · ${formatPlanCategory(plan.category)} · ${formatPlanDuration(plan)} · ${formatPlanPrice(plan)}` } export function GrantSubscriptionDialog({ open, onOpenChange, userId, userName, activeByCategory, onGranted, }: GrantSubscriptionDialogProps) { const [plans, setPlans] = useState([]) const [plansLoading, setPlansLoading] = useState(false) const [planId, setPlanId] = useState("") const [planSearch, setPlanSearch] = useState("") const [planMenuOpen, setPlanMenuOpen] = useState(false) const [recordPayment, setRecordPayment] = useState(true) const [confirmOpen, setConfirmOpen] = useState(false) const [saving, setSaving] = useState(false) const [formError, setFormError] = useState(null) useEffect(() => { if (!open) return setPlanId("") setPlanSearch("") setPlanMenuOpen(false) setRecordPayment(true) setConfirmOpen(false) setFormError(null) setSaving(false) const loadPlans = async () => { setPlansLoading(true) try { const res = await getSubscriptionPlans() setPlans(res.data.filter((plan) => plan.is_active)) } catch (err) { setPlans([]) notifyApiError(err, "Failed to load subscription plans") } finally { setPlansLoading(false) } } void loadPlans() }, [open]) const selectedPlan = useMemo( () => plans.find((p) => String(p.id) === planId) ?? null, [plans, planId], ) const categoryBlocked = selectedPlan != null && activeByCategory[selectedPlan.category] === true const filteredPlans = useMemo(() => { const q = planSearch.trim().toLowerCase() if (!q) return plans return plans.filter((plan) => { const haystack = [ plan.name, plan.category, formatPlanCategory(plan.category), formatPlanDuration(plan), formatPlanPrice(plan), plan.description ?? "", ] .join(" ") .toLowerCase() return haystack.includes(q) }) }, [plans, planSearch]) const handleContinue = (e: React.FormEvent) => { e.preventDefault() setFormError(null) const id = Number(planId) if (!Number.isFinite(id) || id < 1) { setFormError("Select a subscription plan.") return } if (categoryBlocked) { setFormError( "This learner already has an active subscription in that category. Extend the existing plan or cancel it first.", ) return } setPlanMenuOpen(false) setConfirmOpen(true) } const handleConfirmGrant = async () => { const id = Number(planId) if (!Number.isFinite(id) || id < 1 || categoryBlocked) return setSaving(true) try { const res = await adminApplySubscription(userId, { plan_id: id, record_payment: recordPayment, }) toast.success(res.message || "Subscription granted") setConfirmOpen(false) onGranted() onOpenChange(false) } catch (err) { const detail = getApiErrorMessage(err, "Failed to grant subscription") setFormError(detail) setConfirmOpen(false) notifyApiError(err, "Failed to grant subscription") } finally { setSaving(false) } } return ( <> { if (saving) return if (!next) { setConfirmOpen(false) onOpenChange(false) } }} >
Grant subscription Grant plan access {userName ? ` to ${userName}` : ""}. Choose whether to record a payment at the plan price.
{plansLoading ? (
Loading plans…
) : (
{planMenuOpen ? (
setPlanSearch(e.target.value)} placeholder="Search plans…" className="h-9 rounded-lg border-grayScale-200 pl-8 text-sm" autoFocus />
{filteredPlans.map((plan) => { const blocked = activeByCategory[plan.category] === true const selected = String(plan.id) === planId return ( ) })} {filteredPlans.length === 0 ? (

No plans found

) : null}
) : null}
)} {selectedPlan && categoryBlocked ? (

An active {formatPlanCategory(selectedPlan.category)} subscription already exists. Extend or cancel it instead.

) : null}

Payment *

{formError ?

{formError}

: null}
Grant {selectedPlan.name} ( {formatPlanCategory(selectedPlan.category)}) {userName ? ( <> {" "} to {userName} ) : ( " to this learner" )} {recordPayment ? ( <> ? A payment of {formatPlanPrice(selectedPlan)} will be recorded. ) : ( "? No payment will be recorded." )} ) : ( "Grant this subscription?" ) } confirmWord={CONFIRM_WORD} confirmLabel={recordPayment ? "Grant and record payment" : "Grant without payment"} confirming={saving} onConfirm={handleConfirmGrant} /> ) }