import { defineStore } from 'pinia'

export type ActivityStatus = 'draft' | 'scheduled' | 'active' | 'paused' | 'ended'

export type ActivityConfig = {
  audience: string
  conversion: string
  reward: string
  budget: string
}

export type ActivityMetrics = {
  visits: number
  shares: number
  conversions: number
  budgetUsed: number
}

export type ActivityItem = {
  id: number
  name: string
  description: string
  status: ActivityStatus
  startTime: string
  endTime: string
  participants: number
  config: ActivityConfig
  metrics: ActivityMetrics
  createdAt: string
  updatedAt: string
}

const storageKey = 'mosquito-admin-activities-v1'

const safeRead = (): ActivityItem[] | null => {
  try {
    const raw = localStorage.getItem(storageKey)
    return raw ? (JSON.parse(raw) as ActivityItem[]) : null
  } catch {
    return null
  }
}

const safeWrite = (items: ActivityItem[]) => {
  try {
    localStorage.setItem(storageKey, JSON.stringify(items))
  } catch {
    // ignore storage errors in restricted contexts
  }
}

const seedActivities = (): ActivityItem[] => {
  const now = Date.now()
  const iso = (offsetDays: number) => new Date(now + offsetDays * 86400000).toISOString()
  return [
    {
      id: 1,
      name: '裂变增长计划',
      description: '邀请好友注册，获取双倍奖励。',
      status: 'active',
      startTime: iso(-7),
      endTime: iso(21),
      participants: 1280,
      config: {
        audience: '新注册用户与邀请达人',
        conversion: '完成注册并绑定手机号',
        reward: '每邀请 1 人奖励 20 积分',
        budget: '总预算 50,000 积分'
      },
      metrics: {
        visits: 48210,
        shares: 12800,
        conversions: 3840,
        budgetUsed: 32000
      },
      createdAt: iso(-10),
      updatedAt: iso(-1)
    },
    {
      id: 2,
      name: '新用户召回活动',
      description: '召回沉默用户，提升活跃度。',
      status: 'ended',
      startTime: iso(-21),
      endTime: iso(-2),
      participants: 640,
      config: {
        audience: '30 天未登录用户',
        conversion: '完成首次分享',
        reward: '每邀请 1 人奖励 10 积分',
        budget: '总预算 20,000 积分'
      },
      metrics: {
        visits: 18200,
        shares: 6200,
        conversions: 1200,
        budgetUsed: 15000
      },
      createdAt: iso(-25),
      updatedAt: iso(-2)
    }
  ]
}

export const useActivityStore = defineStore('activities', {
  state: () => ({
    items: safeRead() ?? seedActivities()
  }),
  getters: {
    byId: (state) => (id: number) => state.items.find((item) => item.id === id) ?? null
  },
  actions: {
    persist() {
      safeWrite(this.items)
    },
    create(item: Omit<ActivityItem, 'id' | 'createdAt' | 'updatedAt'>) {
      const now = new Date().toISOString()
      const nextId = this.items.length ? Math.max(...this.items.map((i) => i.id)) + 1 : 1
      const created: ActivityItem = {
        ...item,
        id: nextId,
        createdAt: now,
        updatedAt: now
      }
      this.items = [created, ...this.items]
      this.persist()
      return created
    },
    update(id: number, updates: Partial<ActivityItem>) {
      const index = this.items.findIndex((item) => item.id === id)
      if (index < 0) return null
      const updated = {
        ...this.items[index],
        ...updates,
        updatedAt: new Date().toISOString()
      }
      this.items.splice(index, 1, updated)
      this.persist()
      return updated
    },
    updateStatus(id: number, status: ActivityStatus) {
      return this.update(id, { status })
    }
  }
})
