import type { WizardConfig, WizardStepId, CustomField, WizardFieldConfig } from '@/types/wizard-config'

/**
 * Check if a field is visible based on the wizard configuration
 */
export function isFieldVisible(config: WizardConfig, fieldName: string): boolean {
  const fieldConfig = config.fields?.[fieldName]
  if (!fieldConfig) return true // Default visible if not configured
  return fieldConfig.visible !== false
}

/**
 * Check if a field is required based on the wizard configuration
 */
export function isFieldRequired(config: WizardConfig, fieldName: string): boolean {
  const fieldConfig = config.fields?.[fieldName]
  if (!fieldConfig) return false // Default not required if not configured
  return fieldConfig.required === true
}

/**
 * Get field configuration for a specific field
 */
export function getFieldConfig(config: WizardConfig, fieldName: string): WizardFieldConfig | undefined {
  return config.fields?.[fieldName]
}

/**
 * Get visible steps based on configuration and form values
 */
export function getVisibleSteps(config: WizardConfig, formValues: Record<string, unknown>) {
  const steps = config.steps || []

  return steps
    .filter((step) => step.enabled !== false)
    .filter((step) => {
      // Check conditional visibility
      if (!step.conditionalOn) return true

      const { field, operator, value } = step.conditionalOn
      const fieldValue = formValues[field]

      switch (operator) {
        case 'equals':
          return fieldValue === value
        case 'notEquals':
          return fieldValue !== value
        case 'in':
          return Array.isArray(value) && value.includes(fieldValue as string)
        case 'notIn':
          return Array.isArray(value) && !value.includes(fieldValue as string)
        default:
          return true
      }
    })
    .sort((a, b) => a.order - b.order)
}

/**
 * Build steps array with field mappings for validation
 */
export function buildStepsArray(config: WizardConfig) {
  const baseSteps = [
    { id: 'welcome', title: 'Category', fields: ['competitionCategory'] },
    { id: 'contact', title: 'Contact', fields: ['contactName', 'contactEmail', 'contactPhone', 'country', 'city'] },
    { id: 'project', title: 'Project', fields: ['projectName', 'teamName', 'description', 'oceanIssue'] },
    { id: 'team', title: 'Team', fields: ['teamMembers'] },
    { id: 'additional', title: 'Details', fields: ['institution', 'startupCreatedDate', 'wantsMentorship', 'referralSource'] },
    { id: 'review', title: 'Review', fields: ['gdprConsent'] },
  ]

  // Apply config overrides
  return baseSteps.map((step) => {
    const configStep = config.steps?.find((s) => s.id === step.id)
    return {
      ...step,
      title: configStep?.title || step.title,
      enabled: configStep?.enabled !== false,
    }
  })
}

/**
 * Get custom fields for a specific step
 */
export function getCustomFieldsForStep(config: WizardConfig, stepId: WizardStepId): CustomField[] {
  const customFields = config.customFields || []
  return customFields
    .filter((field) => field.stepId === stepId)
    .sort((a, b) => a.order - b.order)
}

/**
 * Parse wizard config from JSON (settingsJson) and merge with defaults
 */
export function parseWizardConfig(settingsJson: unknown): WizardConfig {
  const DEFAULT_WIZARD_CONFIG: WizardConfig = {
    steps: [
      { id: 'welcome', enabled: true, order: 0, title: 'Category' },
      { id: 'contact', enabled: true, order: 1, title: 'Contact' },
      { id: 'project', enabled: true, order: 2, title: 'Project' },
      { id: 'team', enabled: true, order: 3, title: 'Team' },
      { id: 'additional', enabled: true, order: 4, title: 'Details' },
      { id: 'review', enabled: true, order: 5, title: 'Review' },
    ],
    fields: {},
    competitionCategories: [],
    oceanIssues: [],
    features: {
      enableWhatsApp: false,
      enableMentorship: true,
      enableTeamMembers: true,
      requireInstitution: false,
    },
    customFields: [],
  }

  if (!settingsJson || typeof settingsJson !== 'object') {
    return DEFAULT_WIZARD_CONFIG
  }

  return {
    ...DEFAULT_WIZARD_CONFIG,
    ...(settingsJson as Partial<WizardConfig>),
  }
}
