"use client"

import {
  getVendorInventory,
  addVendorInventoryItem,
} from "@/lib/vendor-storage"
import {
  getBookings,
  saveBooking,
  createBookingId,
  createConfirmationCode,
  calculateTaxBreakdown,
  updateBookingSubletStatus,
  type BookingRecord,
  type BookingStatus,
} from "@/lib/booking-storage"
import {
  getVendorQRs,
  addVendorQR,
  type VendorQRType,
} from "@/lib/vendor-qr-storage"
import {
  getVendorCoupons,
  addVendorCoupon,
} from "@/lib/vendor-coupons-storage"
import {
  getVendorEmployees,
  addVendorEmployee,
} from "@/lib/vendor-team-storage"
import {
  getVendorNotifications,
  addVendorNotification,
} from "@/lib/vendor-notifications-storage"
import {
  addBookingTransaction,
  addVendorPayout,
  getVendorPayouts,
} from "@/lib/vendor-wallet-storage"

const SEEDED_KEY = "beachlyfe_vendor_demo_seeded_v1"

function getSeededIds(): string[] {
  if (typeof window === "undefined" || !window.localStorage) return []
  try {
    const raw = localStorage.getItem(SEEDED_KEY)
    return raw ? JSON.parse(raw) : []
  } catch {
    return []
  }
}

function setSeededId(vendorId: string) {
  const ids = getSeededIds()
  if (ids.includes(vendorId)) return
  localStorage.setItem(SEEDED_KEY, JSON.stringify([...ids, vendorId]))
}

export function isVendorDemoSeeded(vendorId: string): boolean {
  return getSeededIds().includes(vendorId)
}

function daysAgo(days: number): string {
  const d = new Date()
  d.setDate(d.getDate() - days)
  return d.toISOString().slice(0, 10)
}

function daysAhead(days: number): string {
  const d = new Date()
  d.setDate(d.getDate() + days)
  return d.toISOString().slice(0, 10)
}

export function seedVendorDemo(vendorId: string): void {
  if (typeof window === "undefined" || !window.localStorage) return
  if (getSeededIds().includes(vendorId)) return

  const today = new Date().toISOString().slice(0, 10)

  // 1. Inventory
  let inventory = getVendorInventory(vendorId)
  if (inventory.length === 0) {
    addVendorInventoryItem(vendorId, {
      name: "Beach Chair",
      description: "Comfortable reclining beach chair with cup holder.",
      category: "rentals",
      images: ["https://images.unsplash.com/photo-1527529482837-4698179dc6ce?w=400"],
      priceHourly: 5,
      priceDaily: 15,
      priceWeekly: 75,
      stockQuantity: 20,
      disabled: false,
    })
    addVendorInventoryItem(vendorId, {
      name: "Umbrella Set",
      description: "Beach umbrella with sand anchor. Fits 2 chairs.",
      category: "rentals",
      images: ["https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=400"],
      priceHourly: null,
      priceDaily: 25,
      priceWeekly: 120,
      stockQuantity: 10,
      disabled: false,
    })
    addVendorInventoryItem(vendorId, {
      name: "Stand-Up Paddleboard",
      description: "Single SUP with paddle and leash. Life vest included.",
      category: "Water Sports",
      images: ["https://images.unsplash.com/photo-1544551763-46a013bb70d5?w=400"],
      priceHourly: 25,
      priceDaily: 75,
      priceWeekly: 350,
      stockQuantity: 4,
      disabled: false,
    })
    inventory = getVendorInventory(vendorId)
  }

  const item = inventory[0]
  if (!item) return

  const taxRates = { state: 0.06, county: 0.02, city: 0.015 }
  type SubletStatus = "none" | "requested" | "approved" | "rejected"
  const makeBooking = (
    status: BookingStatus,
    date: string,
    time: string,
    timeRange?: string,
    customerName?: string,
    customerEmail?: string,
    tip = 0,
    subletStatus?: SubletStatus
  ): BookingRecord => {
    const subtotal = 45
    const discount = 0
    const taxBreakdown = calculateTaxBreakdown(subtotal - discount)
    const total = Math.round((subtotal - discount + taxBreakdown.totalTax + tip) * 100) / 100
    return {
      id: createBookingId(),
      confirmationCode: createConfirmationCode(),
      status,
      itemId: item.id,
      vendorId,
      itemName: item.name,
      date,
      time,
      timeRange,
      quantity: 1,
      subtotal,
      discount,
      taxState: taxBreakdown.taxState,
      taxCounty: taxBreakdown.taxCounty,
      taxCity: taxBreakdown.taxCity,
      tip,
      total,
      createdAt: new Date().toISOString(),
      customerName,
      customerEmail,
      subletStatus: subletStatus ?? "none",
    }
  }

  // 2. Bookings
  const existingBookings = getBookings().filter((b) => b.vendorId === vendorId)
  if (existingBookings.length === 0) {
    const completedBookings: BookingRecord[] = []
    saveBooking(makeBooking("pending", daysAhead(2), "10:00", "10:00 – 14:00", "Alex Rivera", "alex.r@example.com"))
    saveBooking(makeBooking("pending", daysAhead(5), "14:00", undefined, "Jordan Lee", "j.lee@example.com"))
    saveBooking(makeBooking("scheduled", daysAhead(1), "09:00", "09:00 – 17:00", "Sam Taylor", "sam.t@example.com", 5))
    saveBooking(makeBooking("scheduled", daysAhead(3), "11:00", undefined, "Morgan Hill", "morgan@example.com", 0, "requested"))
    saveBooking(makeBooking("active", today, "08:00", "08:00 – 12:00", "Casey Drew", "casey@example.com", 10, "requested"))
    const c1 = makeBooking("completed", daysAgo(2), "10:00", "10:00 – 16:00", "Riley Park", "riley@example.com", 8)
    const c2 = makeBooking("completed", daysAgo(5), "09:00", undefined, "Quinn Bell", "quinn@example.com", 5)
    const c3 = makeBooking("completed", daysAgo(7), "13:00", "13:00 – 17:00", "Avery Scott", "avery@example.com", 12)
    saveBooking(c1)
    completedBookings.push(c1)
    saveBooking(c2)
    completedBookings.push(c2)
    saveBooking(c3)
    completedBookings.push(c3)
    saveBooking(makeBooking("cancelled", daysAhead(4), "15:00", undefined))
    saveBooking(makeBooking("cancelled", daysAgo(1), "10:00", undefined))

    completedBookings.forEach((b) => addBookingTransaction(vendorId, b.id, b.total - b.tip, b.tip))
  }

  // 3. QR codes
  if (getVendorQRs(vendorId).length === 0) {
    addVendorQR(vendorId, { type: "vendor_profile" as VendorQRType, label: "Main kiosk", destination: "vendor/v1/" })
    addVendorQR(vendorId, { type: "inventory_item" as VendorQRType, label: "Chair stand A", destination: "/item/" + item.id })
    addVendorQR(vendorId, { type: "vendor_profile" as VendorQRType, label: "Tent sign", destination: "/vendor/" + vendorId })
  }

  // 4. Coupons
  if (getVendorCoupons(vendorId).length === 0) {
    addVendorCoupon(vendorId, {
      code: "BEACH15",
      discountType: "percent",
      discountValue: 15,
      expiryDate: daysAhead(30),
      maxUses: 100,
      itemIds: [],
    })
    addVendorCoupon(vendorId, {
      code: "WEEKEND10",
      discountType: "percent",
      discountValue: 10,
      expiryDate: daysAhead(14),
      maxUses: 50,
      itemIds: [],
    })
  }

  // 5. Employees
  if (getVendorEmployees(vendorId).length === 0) {
    addVendorEmployee(vendorId, { name: "Jamie Cox", role: "Lead", status: "active" })
    addVendorEmployee(vendorId, { name: "Skyler Reed", role: "Attendant", status: "active" })
    addVendorEmployee(vendorId, { name: "Jordan Blake", role: "Attendant", status: "inactive" })
  }

  // 6. Notifications
  if (getVendorNotifications(vendorId).length === 0) {
    addVendorNotification(vendorId, {
      type: "new_booking",
      title: "New booking request",
      body: "Alex Rivera requested a booking for Beach Chair. Accept or reject in Bookings.",
    })
    addVendorNotification(vendorId, {
      type: "payout",
      title: "Payout completed",
      body: "Your weekly payout of $127.50 has been sent to your bank account.",
    })
    addVendorNotification(vendorId, {
      type: "admin_message",
      title: "Welcome to BeachLyfe",
      body: "Your vendor account is approved. Add inventory and start accepting bookings.",
    })
    addVendorNotification(vendorId, {
      type: "subscription_renewal",
      title: "Subscription renewal",
      body: "Your plan renews in 28 days. Upgrade anytime for lower commission.",
    })
    addVendorNotification(vendorId, {
      type: "new_booking",
      title: "New booking request",
      body: "Jordan Lee requested a booking. View in New Orders.",
    })
  }

  // 7. One past payout
  if (getVendorPayouts(vendorId).length === 0) {
    addVendorPayout(vendorId, {
      amount: 89.25,
      status: "completed",
      scheduledFor: daysAgo(7),
      completedAt: daysAgo(7),
    })
  }

  setSeededId(vendorId)
}

/** Backfill sublet requests for vendors already seeded (so they see mock sublet requests). */
export function ensureVendorSubletMocks(vendorId: string): void {
  if (typeof window === "undefined" || !window.localStorage) return
  const all = getBookings().filter((b) => b.vendorId === vendorId)
  const hasRequested = all.some((b) => b.subletStatus === "requested")
  if (hasRequested) return
  const candidates = all.filter(
    (b) =>
      (b.status === "active" || b.status === "scheduled") &&
      (!b.subletStatus || b.subletStatus === "none")
  )
  candidates.slice(0, 2).forEach((b) => updateBookingSubletStatus(b.id, "requested"))
}
