import { ref, readonly } from 'vue'
import { useApi } from '../../composables/useApi'

export interface Plan {
  id: string
  name: string
  description?: string
  stripe_price_id: string
  stripe_seat_price_id?: string
  price_cents: number
  currency: string
  interval: 'monthly' | 'yearly' | 'one_time'
  included_seats: number
  features: Record<string, boolean>
  limits: Record<string, number>
  trial_days?: number
  is_active: boolean
  sort_order: number
  created_at: number
  updated_at: number
}

export interface CreatePlanRequest {
  id: string
  name: string
  description?: string
  stripe_price_id: string
  stripe_seat_price_id?: string
  price_cents: number
  currency: string
  interval: 'monthly' | 'yearly' | 'one_time'
  included_seats: number
  features: Record<string, boolean>
  limits: Record<string, number>
  trial_days?: number
  is_active?: boolean
  sort_order?: number
}

export interface UpdatePlanRequest {
  name?: string
  description?: string
  stripe_price_id?: string
  stripe_seat_price_id?: string
  price_cents?: number
  currency?: string
  interval?: 'monthly' | 'yearly' | 'one_time'
  included_seats?: number
  features?: Record<string, boolean>
  limits?: Record<string, number>
  trial_days?: number
  is_active?: boolean
  sort_order?: number
}

export interface PlanExport {
  version: string
  exported_at: string
  plans: Plan[]
}

export type ImportConflictStrategy = 'error' | 'skip' | 'update'

export interface ImportPlanRequest {
  plans: Plan[]
  conflict_strategy: ImportConflictStrategy
}

export interface ImportResult {
  created: number
  updated: number
  skipped: number
  errors: string[]
}

export function usePlans() {
  const api = useApi()
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  const plans = ref<Plan[]>([])
  const currentPlan = ref<Plan | null>(null)

  async function fetchPlans(includeInactive = false): Promise<Plan[]> {
    isLoading.value = true
    error.value = null

    try {
      const endpoint = includeInactive ? '/admin/billing/plans' : '/billing/public/plans'
      const response = await api.get<{ plans: Plan[] }>(endpoint)
      plans.value = response.plans
      return response.plans
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Failed to fetch plans'
      return []
    } finally {
      isLoading.value = false
    }
  }

  async function fetchPlan(planId: string): Promise<Plan | null> {
    isLoading.value = true
    error.value = null

    try {
      const response = await api.get<Plan>(`/admin/billing/plans/${encodeURIComponent(planId)}`)
      currentPlan.value = response
      return response
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Failed to fetch plan'
      return null
    } finally {
      isLoading.value = false
    }
  }

  async function createPlan(request: CreatePlanRequest): Promise<Plan | null> {
    isLoading.value = true
    error.value = null

    try {
      const response = await api.post<Plan>('/admin/billing/plans', request)
      // Refresh plans list
      await fetchPlans(true)
      return response
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Failed to create plan'
      throw e
    } finally {
      isLoading.value = false
    }
  }

  async function updatePlan(planId: string, request: UpdatePlanRequest): Promise<Plan | null> {
    isLoading.value = true
    error.value = null

    try {
      const response = await api.put<Plan>(`/admin/billing/plans/${encodeURIComponent(planId)}`, request)
      currentPlan.value = response
      // Refresh plans list
      await fetchPlans(true)
      return response
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Failed to update plan'
      throw e
    } finally {
      isLoading.value = false
    }
  }

  async function deletePlan(planId: string): Promise<void> {
    isLoading.value = true
    error.value = null

    try {
      await api.delete(`/admin/billing/plans/${encodeURIComponent(planId)}`)
      // Refresh plans list
      await fetchPlans(true)
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Failed to delete plan'
      throw e
    } finally {
      isLoading.value = false
    }
  }

  async function setActive(planId: string, isActive: boolean): Promise<void> {
    isLoading.value = true
    error.value = null

    try {
      await api.post(`/admin/billing/plans/${encodeURIComponent(planId)}/active`, { is_active: isActive })
      // Refresh plans list
      await fetchPlans(true)
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Failed to update plan status'
      throw e
    } finally {
      isLoading.value = false
    }
  }

  async function exportPlans(): Promise<PlanExport | null> {
    isLoading.value = true
    error.value = null

    try {
      const response = await api.get<PlanExport>('/admin/billing/plans/export')
      return response
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Failed to export plans'
      return null
    } finally {
      isLoading.value = false
    }
  }

  async function importPlans(request: ImportPlanRequest): Promise<ImportResult | null> {
    isLoading.value = true
    error.value = null

    try {
      const response = await api.post<ImportResult>('/admin/billing/plans/import', request)
      // Refresh plans list after import
      await fetchPlans(true)
      return response
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Failed to import plans'
      throw e
    } finally {
      isLoading.value = false
    }
  }

  function downloadExport(exportData: PlanExport): void {
    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `plans-export-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  return {
    // State
    plans: readonly(plans),
    currentPlan: readonly(currentPlan),
    isLoading: readonly(isLoading),
    error: readonly(error),

    // Actions
    fetchPlans,
    fetchPlan,
    createPlan,
    updatePlan,
    deletePlan,
    setActive,
    exportPlans,
    importPlans,
    downloadExport,
  }
}
