"use client"

export interface VendorCoupon {
  id: string
  vendorId: string
  code: string
  discountType: "percent" | "fixed"
  discountValue: number
  expiryDate: string
  maxUses: number
  usedCount: number
  itemIds: string[] // empty = all items
  createdAt: string
}

export interface CouponRedemption {
  id: string
  couponId: string
  bookingId: string
  usedAt: string
}

const COUPONS_KEY = "beachlyfe_vendor_coupons_v1"
const REDEMPTIONS_KEY = "beachlyfe_vendor_coupon_redemptions_v1"

function canUse() {
  return typeof window !== "undefined" && window.localStorage != null
}

function genId(prefix: string) {
  return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`
}

function getCoupons(): VendorCoupon[] {
  if (!canUse()) return []
  try {
    const raw = localStorage.getItem(COUPONS_KEY)
    return raw ? JSON.parse(raw) : []
  } catch {
    return []
  }
}

function saveCoupons(list: VendorCoupon[]) {
  localStorage.setItem(COUPONS_KEY, JSON.stringify(list))
}

export function getVendorCoupons(vendorId: string): VendorCoupon[] {
  return getCoupons().filter((c) => c.vendorId === vendorId)
}

export function addVendorCoupon(
  vendorId: string,
  data: Omit<VendorCoupon, "id" | "vendorId" | "usedCount" | "createdAt">
): VendorCoupon {
  const coupon: VendorCoupon = {
    ...data,
    id: genId("cpn"),
    vendorId,
    usedCount: 0,
    createdAt: new Date().toISOString(),
  }
  const list = getCoupons()
  list.push(coupon)
  saveCoupons(list)
  return coupon
}

export function getVendorCouponById(couponId: string, vendorId: string): VendorCoupon | null {
  return getCoupons().find((c) => c.id === couponId && c.vendorId === vendorId) ?? null
}

export function updateVendorCoupon(
  couponId: string,
  vendorId: string,
  updates: Partial<Pick<VendorCoupon, "code" | "discountType" | "discountValue" | "expiryDate" | "maxUses" | "itemIds">>
): VendorCoupon | null {
  const list = getCoupons()
  const idx = list.findIndex((c) => c.id === couponId && c.vendorId === vendorId)
  if (idx < 0) return null
  list[idx] = { ...list[idx], ...updates }
  saveCoupons(list)
  return list[idx]
}

export function deleteVendorCoupon(couponId: string, vendorId: string): boolean {
  const list = getCoupons()
  const next = list.filter((c) => !(c.id === couponId && c.vendorId === vendorId))
  if (next.length === list.length) return false
  saveCoupons(list)
  return true
}

export function getRedemptions(couponId: string): CouponRedemption[] {
  if (!canUse()) return []
  try {
    const raw = localStorage.getItem(REDEMPTIONS_KEY)
    const list: CouponRedemption[] = raw ? JSON.parse(raw) : []
    return list.filter((r) => r.couponId === couponId)
  } catch {
    return []
  }
}
