import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'

import type { BusinessPrimaryColorId } from '../utils/businessPrimaryColors'

export interface BrandingSettings {
  primaryColor: BusinessPrimaryColorId
  defaultLocale?: 'en' | 'fa'
}

export interface DashboardSettings {
  comments: { autoApprove: boolean }
  expertReviews: { autoApprove: boolean }
}

export interface OrderProcessStep {
  id: string
  label: string
  labelFa: string
  color: string
}

export interface StoreSettings {
  onlineSellEnabled: boolean
  orderProcessSteps: OrderProcessStep[]
}

export interface BusinessSettings {
  branding: BrandingSettings
  dashboard: DashboardSettings
  store: StoreSettings
}

export interface SettingsResponse {
  businessId: string
  settings: BusinessSettings
}

export const DEFAULT_ORDER_PROCESS_STEPS: OrderProcessStep[] = [
  {
    id: 'processing',
    label: 'Under processing',
    labelFa: 'در حال پردازش',
    color: '#3B82F6',
  },
  {
    id: 'ready-for-shipping',
    label: 'Ready for shipping',
    labelFa: 'آماده ارسال',
    color: '#F59E0B',
  },
  {
    id: 'shipped',
    label: 'Shipped',
    labelFa: 'ارسال‌شده',
    color: '#8B5CF6',
  },
  {
    id: 'delivered',
    label: 'Delivered',
    labelFa: 'تحویل‌شده',
    color: '#22C55E',
  },
]

function settingsPath() {
  const businessId = getActiveBusinessId()
  if (!businessId) {
    throw new Error('No active business selected. Please sign in again.')
  }
  return `/businesses/${businessId}/settings`
}

export async function getSettings(signal?: AbortSignal) {
  return apiRequest<SettingsResponse>(settingsPath(), { auth: true, signal })
}

export async function updateDashboardSettings(
  dashboard: Partial<DashboardSettings>,
) {
  return apiRequest<SettingsResponse>(settingsPath(), {
    method: 'PATCH',
    auth: true,
    body: { dashboard },
  })
}

export async function updateStoreSettings(store: Partial<StoreSettings>) {
  return apiRequest<SettingsResponse>(settingsPath(), {
    method: 'PATCH',
    auth: true,
    body: { store },
  })
}
