import { t } from '@/lib/i18n'
import { useSettings } from './useSettings'
import { useCreditsStatus } from './useUsage'
import { useIndexingStatus } from './useKnowledgeBase'
import { useQuery } from '@tanstack/react-query'
import { apiClient } from '@/api/client'
import { formatCredits } from '@/utils/formatters'
import { useLanguage } from '@/contexts/LanguageContext'

/**
 * Represents a single critical step in the setup wizard completion checklist.
 */
export interface CriticalStep {
  id: string
  /** Hebrew display name */
  name: string
  /** Whether this step is completed */
  completed: boolean
  /** Hebrew description — shows current status or what's missing */
  description: string
  /** Optional link to the page where the user can complete this step */
  link?: string
}

/**
 * Aggregates all critical setup steps and returns a unified completion status.
 *
 * Critical steps:
 *   1. Bot Active      — settings.is_active
 *   2. Credits          — boost_credits.total > 0
 *   3. Brand Card       — brand_card has company_name filled
 *   4. Indexing          — last_full_index is set OR total_indexed > 0
 *   5. Global Appearance — wizard_progress.global_appearance flag
 *   6. Global Settings   — wizard_progress.global_settings flag
 *
 * This hook is reusable — used by both SetupWizardTab and the floating wizard indicator.
 */
export function useWizardCompletionStatus() {
  const { data: settingsData } = useSettings()
  const settings = settingsData?.data
  const { currentLanguage } = useLanguage()

  const creditsQuery = useCreditsStatus()
  const credits = creditsQuery.data

  const indexingQuery = useIndexingStatus()
  const indexData = indexingQuery.data?.data

  const brandCardQuery = useQuery({
    queryKey: ['brand-card', currentLanguage],
    queryFn: () => apiClient.get<{ data: { brand_card: { company_name?: string } } }>(
      `brand-card${currentLanguage ? `?language=${currentLanguage}` : ''}`
    ),
    staleTime: 30_000,
  })
  const brandCard = brandCardQuery.data?.data?.brand_card

  const wizardProgress = settings?.wizard_progress || {}

  const criticalSteps: CriticalStep[] = [
    {
      id: 'bot_active',
      name: t('Bot Active'),
      completed: Boolean(settings?.is_active),
      description: settings?.is_active
        ? t('Bot is active and ready')
        : t('Bot must be enabled in step 1'),
      link: '/settings',
    },
    {
      id: 'credits',
      name: 'BoostCoin',
      completed: (credits?.boost_credits?.total ?? 0) > 0,
      description: (credits?.boost_credits?.total ?? 0) > 0
        ? `${formatCredits(credits?.boost_credits?.remaining ?? 0)} ${t('BoostCoin available')}`
        : t('BoostCoin must be purchased to use AI'),
      link: '/usage',
    },
    {
      id: 'brand_card',
      name: t('Business Card'),
      completed: Boolean(brandCard?.company_name),
      description: brandCard?.company_name
        ? t('Business details filled')
        : t('Fill in business details so the bot knows your business'),
      link: '/brand-card',
    },
    {
      id: 'indexing',
      name: t('Knowledge Base'),
      completed: Boolean(indexData?.last_full_index) || (indexData?.index_stats?.total_indexed ?? 0) > 0,
      description: (indexData?.index_stats?.total_indexed ?? 0) > 0
        ? `${indexData?.index_stats?.total_indexed} ${t('items indexed')}`
        : t('Index site content so the bot can answer questions'),
      link: '/knowledge-base',
    },
    {
      id: 'global_rules',
      name: t('Global Rules'),
      completed: Boolean(wizardProgress.global_rules),
      description: wizardProgress.global_rules
        ? t('Rules and forbidden topics reviewed')
        : t('Recommended to set global rules and forbidden topics'),
      link: '/bots',
    },
    {
      id: 'global_appearance_colors',
      name: t('Global Colors'),
      completed: Boolean(wizardProgress.global_appearance_colors),
      description: wizardProgress.global_appearance_colors
        ? t('Global colors configured')
        : t('Recommended to set global colors (or import from Elementor)'),
      link: '/appearance-presets',
    },
    {
      id: 'global_appearance_typography',
      name: t('Global Typography'),
      completed: Boolean(wizardProgress.global_appearance_typography),
      description: wizardProgress.global_appearance_typography
        ? t('Global typography configured')
        : t('Recommended to set global fonts (or import from Elementor)'),
      link: '/appearance-presets',
    },
    {
      id: 'general_settings',
      name: t('General Settings'),
      completed: Boolean(wizardProgress.general_settings),
      description: wizardProgress.general_settings
        ? t('General settings reviewed')
        : t('Recommended to review general settings, mobile and limits'),
      link: '/settings',
    },
  ]

  const completedCount = criticalSteps.filter(s => s.completed).length
  const isReady = criticalSteps.every(s => s.completed)

  return {
    /** True when ALL critical steps are satisfied */
    isReady,
    /** Array of all critical steps with their status */
    criticalSteps,
    /** Number of completed critical steps */
    completedCount,
    /** Total number of critical steps */
    totalCritical: criticalSteps.length,
    /** True while any data source is still loading */
    isLoading: creditsQuery.isLoading || brandCardQuery.isLoading || indexingQuery.isLoading,
  }
}
