'use client'; import { useEffect, useMemo, useState } from 'react'; import { Tag, Plus, RefreshCw, Search, CheckCircle2, Trash2, Edit2, Calendar, Users, ShoppingBag, Percent, Copy, Info, ExternalLink, } from 'lucide-react'; import { toast } from 'sonner'; import { format } from 'date-fns'; import { apiFetch } from '@/services/api/client'; import { SlideOver } from '@/components/ui/SlideOver'; import { CustomSelect } from '@/components/ui/CustomSelect'; import { TablePagination, useClientPagination } from '@/components/ui/TablePagination'; interface CouponItem { coupon_id: string; code: string; description: string | null; discount_type: 'PERCENT' | 'FIXED'; discount_value: number; min_order_amount: number; max_discount_cap: number | null; first_order_only: boolean; channel_scope: 'ALL' | 'STOREFRONT' | 'STORE_POS'; usage_limit_total: number | null; usage_limit_per_customer: number; current_usage_count: number; applicable_category_ids: string[]; applicable_brand_ids: string[]; applicable_model_ids: string[]; start_date: string | null; end_date: string | null; is_active: boolean; created_at: string; updated_at: string; } interface CouponUsageAudit { usage_id: string; customer_id: string; order_id: string; discount_amount: number; used_at: string; } type FilterTab = 'all' | 'active' | 'first_order' | 'inactive'; export default function AdminCouponsPage() { const [coupons, setCoupons] = useState([]); const [loading, setLoading] = useState(true); const [searchQuery, setSearchQuery] = useState(''); const [activeTab, setActiveTab] = useState('all'); // SlideOver form state const [showFormModal, setShowFormModal] = useState(false); const [editingCouponId, setEditingCouponId] = useState(null); const [saving, setSaving] = useState(false); // Form Fields const [code, setCode] = useState(''); const [description, setDescription] = useState(''); const [discountType, setDiscountType] = useState<'PERCENT' | 'FIXED'>('PERCENT'); const [discountValue, setDiscountValue] = useState(10); const [minOrderAmount, setMinOrderAmount] = useState(0); const [maxDiscountCap, setMaxDiscountCap] = useState(''); const [firstOrderOnly, setFirstOrderOnly] = useState(false); const [channelScope, setChannelScope] = useState<'ALL' | 'STOREFRONT' | 'STORE_POS'>('ALL'); const [usageLimitTotal, setUsageLimitTotal] = useState(''); const [usageLimitPerCustomer, setUsageLimitPerCustomer] = useState(1); const [startDate, setStartDate] = useState(''); const [endDate, setEndDate] = useState(''); const [isActive, setIsActive] = useState(true); // Usage Audit Drawer state const [inspectCoupon, setInspectCoupon] = useState(null); const [usagesList, setUsagesList] = useState([]); const [usagesLoading, setUsagesLoading] = useState(false); const [totalDiscountGiven, setTotalDiscountGiven] = useState(0); const fetchCoupons = async () => { setLoading(true); try { const data = await apiFetch('/api/v1/admin/coupons'); setCoupons(Array.isArray(data) ? data : []); } catch (err: any) { toast.error(err.message || 'Failed to load promotional coupons'); } finally { setLoading(false); } }; useEffect(() => { fetchCoupons(); }, []); const openCreateModal = () => { setEditingCouponId(null); setCode(''); setDescription(''); setDiscountType('PERCENT'); setDiscountValue(10); setMinOrderAmount(0); setMaxDiscountCap(''); setFirstOrderOnly(false); setChannelScope('ALL'); setUsageLimitTotal(''); setUsageLimitPerCustomer(1); setStartDate(''); setEndDate(''); setIsActive(true); setShowFormModal(true); }; const openEditModal = (coupon: CouponItem) => { setEditingCouponId(coupon.coupon_id); setCode(coupon.code); setDescription(coupon.description || ''); setDiscountType(coupon.discount_type); setDiscountValue(coupon.discount_value); setMinOrderAmount(coupon.min_order_amount || 0); setMaxDiscountCap(coupon.max_discount_cap ?? ''); setFirstOrderOnly(coupon.first_order_only); setChannelScope(coupon.channel_scope); setUsageLimitTotal(coupon.usage_limit_total ?? ''); setUsageLimitPerCustomer(coupon.usage_limit_per_customer || 1); setStartDate(coupon.start_date ? coupon.start_date.substring(0, 10) : ''); setEndDate(coupon.end_date ? coupon.end_date.substring(0, 10) : ''); setIsActive(coupon.is_active); setShowFormModal(true); }; const handleFormSubmit = async (e: React.FormEvent) => { e.preventDefault(); const cleanCode = code.trim().toUpperCase(); if (!cleanCode) { toast.error('Coupon code is required'); return; } if (Number(discountValue) <= 0) { toast.error('Discount value must be greater than zero'); return; } setSaving(true); try { const payload: any = { code: cleanCode, description: description.trim() || undefined, discount_type: discountType, discount_value: Number(discountValue), min_order_amount: Number(minOrderAmount || 0), max_discount_cap: maxDiscountCap !== '' ? Number(maxDiscountCap) : null, first_order_only: firstOrderOnly, channel_scope: channelScope, usage_limit_total: usageLimitTotal !== '' ? Number(usageLimitTotal) : null, usage_limit_per_customer: Number(usageLimitPerCustomer || 1), start_date: startDate ? new Date(startDate).toISOString() : null, end_date: endDate ? new Date(endDate + 'T23:59:59').toISOString() : null, is_active: isActive, }; if (editingCouponId) { await apiFetch(`/api/v1/admin/coupons/${editingCouponId}`, { method: 'PUT', body: JSON.stringify(payload), }); toast.success(`Coupon ${cleanCode} updated successfully`); } else { await apiFetch('/api/v1/admin/coupons', { method: 'POST', body: JSON.stringify(payload), }); toast.success(`Coupon ${cleanCode} created successfully`); } setShowFormModal(false); fetchCoupons(); } catch (err: any) { toast.error(err.message || 'Failed to save coupon'); } finally { setSaving(false); } }; const handleDeleteCoupon = async (coupon: CouponItem) => { if (!confirm(`Are you sure you want to delete or deactivate coupon "${coupon.code}"?`)) { return; } try { const res = await apiFetch(`/api/v1/admin/coupons/${coupon.coupon_id}`, { method: 'DELETE', }); toast.success(res.message || `Coupon ${coupon.code} removed`); fetchCoupons(); } catch (err: any) { toast.error(err.message || 'Failed to remove coupon'); } }; const handleToggleStatus = async (coupon: CouponItem) => { try { await apiFetch(`/api/v1/admin/coupons/${coupon.coupon_id}`, { method: 'PUT', body: JSON.stringify({ is_active: !coupon.is_active }), }); toast.success(`Coupon ${coupon.code} marked ${!coupon.is_active ? 'Active' : 'Inactive'}`); fetchCoupons(); } catch (err: any) { toast.error(err.message || 'Failed to change coupon status'); } }; const openUsagesDrawer = async (coupon: CouponItem) => { setInspectCoupon(coupon); setUsagesLoading(true); try { const res = await apiFetch(`/api/v1/admin/coupons/${coupon.coupon_id}/usages`); setUsagesList(res.usages || []); setTotalDiscountGiven(res.total_discount_given || 0); } catch { toast.error('Failed to load redemption audits'); } finally { setUsagesLoading(false); } }; const copyToClipboard = (text: string) => { navigator.clipboard.writeText(text); toast.success(`Copied "${text}" to clipboard`); }; const filteredCoupons = useMemo(() => { const q = searchQuery.trim().toLowerCase(); return coupons.filter((c) => { const tabMatch = activeTab === 'all' || (activeTab === 'active' && c.is_active) || (activeTab === 'first_order' && c.first_order_only) || (activeTab === 'inactive' && !c.is_active); const searchMatch = !q || c.code.toLowerCase().includes(q) || (c.description && c.description.toLowerCase().includes(q)); return tabMatch && searchMatch; }); }, [coupons, searchQuery, activeTab]); const pager = useClientPagination(filteredCoupons); const inputClass = 'w-full h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary'; const labelClass = 'block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5'; const primaryButton = 'inline-flex items-center justify-center gap-2 h-9 px-4 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer disabled:opacity-50'; const secondaryButton = 'inline-flex items-center justify-center gap-2 h-9 px-4 crm-radius-control border border-border bg-card text-foreground text-[13px] font-medium hover:bg-muted cursor-pointer disabled:opacity-50'; return (
{/* Page Header */}

Promotions & Coupon Rules

{coupons.length}

Create rule-driven coupon codes, first-time customer checkout discounts, and walk-in POS counter promotions.

{/* Main Container */}
setSearchQuery(e.target.value)} className="w-full h-9 pl-9 pr-3 crm-radius-control border border-border bg-card text-[13px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:border-primary transition-colors" />
{( [ { id: 'all', label: `All (${coupons.length})` }, { id: 'active', label: `Active (${coupons.filter((c) => c.is_active).length})` }, { id: 'first_order', label: `1st Order Only (${coupons.filter((c) => c.first_order_only).length})` }, { id: 'inactive', label: `Inactive (${coupons.filter((c) => !c.is_active).length})` }, ] as { id: FilterTab; label: string }[] ).map((tab) => ( ))}
{loading ? (
Loading coupons...
) : (
{filteredCoupons.length === 0 ? ( ) : ( pager.items.map((coupon) => ( )) )}
Coupon code Discount rule Channel & Limits Redemptions Status Action
{searchQuery || activeTab !== 'all' ? 'No coupons match your filter.' : 'No promotional coupons found.'}
{coupon.code}
{coupon.description && (

{coupon.description}

)} {coupon.first_order_only && (
⭐ 1st Order Customer Only
)}
{coupon.discount_type === 'PERCENT' ? `${coupon.discount_value}% OFF` : `₹${coupon.discount_value.toFixed(2)} FLAT OFF`}
{coupon.max_discount_cap && (

Max discount: ₹{coupon.max_discount_cap}

)}

Min order: ₹{coupon.min_order_amount || 0}

{coupon.channel_scope === 'ALL' ? '🌐 Global Omnichannel' : coupon.channel_scope === 'STOREFRONT' ? '💻 Storefront Online' : '🏬 Walk-in POS'}

Limit per user: {coupon.usage_limit_per_customer || 1}

{coupon.usage_limit_total && (

Max {coupon.usage_limit_total} total

)}
)}
{/* SlideOver for Create / Edit Coupon */} setShowFormModal(false)} title={editingCouponId ? `Edit Coupon ${code}` : 'Create Promotional Coupon'} icon={} >
setCode(e.target.value.toUpperCase())} placeholder="e.g. WELCOME10 or FLAT200" className={`${inputClass} font-mono uppercase font-bold tracking-wider`} />
setDescription(e.target.value)} placeholder="e.g. 10% off for first time customer checkout" className={inputClass} />
setDiscountType(val as any)} options={[ { value: 'PERCENT', label: 'Percentage (%) Off' }, { value: 'FIXED', label: 'Flat (₹) Amount Off' }, ]} />
setDiscountValue(Number(e.target.value))} className={inputClass} />
{discountType === 'PERCENT' && (
setMaxDiscountCap(e.target.value === '' ? '' : Number(e.target.value))} placeholder="e.g. 500 (Leave empty for no cap)" className={inputClass} />
)}
setMinOrderAmount(Number(e.target.value))} placeholder="e.g. 999" className={inputClass} />
{/* 🌟 First-time Customer Checkout Rule */}

1st Time Customer Only

Restricts this coupon to customers making their very first order.

setFirstOrderOnly(e.target.checked)} className="w-4 h-4 text-primary rounded border-border cursor-pointer" />
setChannelScope(val as any)} options={[ { value: 'ALL', label: '🌐 All Channels (Storefront & Walk-in POS)' }, { value: 'STOREFRONT', label: '💻 Storefront Online Checkout Only' }, { value: 'STORE_POS', label: '🏬 Walk-in Counter POS Only' }, ]} />
setUsageLimitTotal(e.target.value === '' ? '' : Number(e.target.value))} placeholder="Unlimited" className={inputClass} />
setUsageLimitPerCustomer(Number(e.target.value))} className={inputClass} />
setStartDate(e.target.value)} className={inputClass} />
setEndDate(e.target.value)} className={inputClass} />
setIsActive(e.target.checked)} className="w-4 h-4 text-primary rounded border-border cursor-pointer" />
{/* SlideOver for Redemption Audits */} setInspectCoupon(null)} title={inspectCoupon ? `Redemptions for ${inspectCoupon.code}` : 'Coupon Usages'} icon={} >

{inspectCoupon?.code}

Total Redemptions: {usagesList.length}

Total Savings

₹{totalDiscountGiven.toFixed(2)}

{usagesLoading ? (
Loading audit log...
) : usagesList.length === 0 ? (
No redemptions recorded for this coupon yet.
) : (
{usagesList.map((usage) => (
Order ID: {usage.order_id} -₹{Number(usage.discount_amount).toFixed(2)}
Customer: {usage.customer_id} {usage.used_at ? format(new Date(usage.used_at), 'dd-MMM-yyyy HH:mm') : '—'}
))}
)}
); }