const chalk = require('chalk')
const inquirer = require('inquirer')
const { getConfig, setConfig } = require('../lib/config')
const { getApps, getWebs } = require('../lib/api')

async function useCommand() {
  try {
    const config = getConfig()
    const cmsUrl = config.cmsUrl

    if (!cmsUrl) {
      console.error(chalk.red('Error: CMS URL not configured. Run "bild init" first.'))
      process.exit(1)
    }

    console.log(chalk.blue('Fetching apps and websites...\n'))

    try {
      // Get apps (React Native)
      const apps = await getApps()
      
      // Get websites (React/Next.js)
      const webs = await getWebs()

      const allItems = []
      
      // Process apps
      if (Array.isArray(apps)) {
        apps.forEach((app) => {
          allItems.push({
            id: app.id || app,
            name: app.name || app.id || 'Unnamed App',
            description: app.description,
            type: 'App',
            typeLabel: 'App',
          })
        })
      } else if (apps && typeof apps === 'object') {
        Object.entries(apps).forEach(([id, app]) => {
          if (typeof app === 'object' && app !== null) {
            allItems.push({
              id: app.id || id,
              name: app.name || id,
              description: app.description,
              type: 'App',
              typeLabel: 'App',
            })
          }
        })
      }

      // Process websites
      if (Array.isArray(webs)) {
        webs.forEach((web) => {
          allItems.push({
            id: web.id || web,
            name: web.name || web.id || 'Unnamed Website',
            description: web.description,
            type: 'Website',
            typeLabel: 'Website',
          })
        })
      } else if (webs && typeof webs === 'object') {
        Object.entries(webs).forEach(([id, web]) => {
          if (typeof web === 'object' && web !== null) {
            allItems.push({
              id: web.id || id,
              name: web.name || id,
              description: web.description,
              type: 'Website',
              typeLabel: 'Website',
            })
          }
        })
      }

      if (allItems.length === 0) {
        console.log(chalk.yellow('No apps or websites found.'))
        process.exit(1)
      }

      // Sort items: Websites first, then Apps, then alphabetically by name
      allItems.sort((a, b) => {
        if (a.type !== b.type) {
          return a.type === 'Website' ? -1 : 1
        }
        return (a.name || a.id).localeCompare(b.name || b.id)
      })

      const prompt = inquirer.createPromptModule()
      const currentDefault = config.defaultAppId
      
      const choices = allItems.map((item) => {
        const displayName = `${item.typeLabel}: ${chalk.bold(item.name || item.id)}${item.description ? ` - ${item.description}` : ''}`
        const isCurrent = item.id === currentDefault
        return {
          name: isCurrent ? `${displayName} ${chalk.gray('(current default)')}` : displayName,
          value: item.id,
          short: `${item.typeLabel}: ${item.name || item.id}`,
        }
      })

      const { selectedAppId } = await prompt([
        {
          type: 'list',
          name: 'selectedAppId',
          message: 'Select an app or website to use as default:',
          choices,
          pageSize: 20,
        },
      ])

      setConfig('defaultAppId', selectedAppId)
      
      const selectedItem = allItems.find(item => item.id === selectedAppId)
      console.log(chalk.green(`\n✓ Set default app/website to: ${chalk.bold(selectedItem.name || selectedAppId)} (${selectedItem.type})`))
      console.log(chalk.gray(`   ID: ${selectedAppId}`))
    } catch (error) {
      console.error(chalk.red(`Failed to fetch apps: ${error.message}`))
      if (error.response) {
        console.error(chalk.red(`Status: ${error.response.status}`))
        console.error(chalk.red(`Response: ${JSON.stringify(error.response.data)}`))
      }
      process.exit(1)
    }
  } catch (error) {
    console.error(chalk.red(`Failed to select app: ${error.message}`))
    process.exit(1)
  }
}

module.exports = useCommand

