const chalk = require('chalk')
const { getConfig } = require('../lib/config')
const { listCodeLibraries } = require('../lib/api')

function normalizeItems(templateLibs) {
  if (!templateLibs || (Array.isArray(templateLibs) && templateLibs.length === 0)) {
    return []
  }
  const items = Array.isArray(templateLibs)
    ? templateLibs
    : Object.entries(templateLibs).map(([id, item]) => ({
        id,
        ...item,
      }))
  return items
}

/**
 * List Templates: compact Template ID + name by default; full detail with --verbose
 * (replaces former `bild list-code-libs`).
 */
async function libraryListCommand(options) {
  try {
    const config = getConfig()

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

    const appId = options.appId || config.defaultAppId

    if (!appId) {
      console.error(chalk.red('Error: App ID is required. Use --app-id <id> or set defaultAppId in config.'))
      process.exit(1)
    }

    let templateLibs
    try {
      templateLibs = await listCodeLibraries(appId)
    } catch (error) {
      console.error(chalk.red(`Failed to list templates: ${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)
    }

    const items = normalizeItems(templateLibs)

    if (items.length === 0) {
      console.log(chalk.yellow('No templates found.'))
      return
    }

    if (options.verbose) {
      console.log(chalk.blue(`Fetching templates for app ${chalk.bold(appId)}...\n`))

      console.log(chalk.bold('Templates:\n'))
      console.log(chalk.gray('─'.repeat(80)))

      items.forEach((item) => {
        const id = item.id || item.templateId || item.snippetId || 'N/A'
        console.log(`${chalk.cyan('Template ID')}: ${chalk.bold(id)}`)

        if (item.name) {
          console.log(`  ${chalk.gray('Name')}: ${item.name}`)
        }

        const snippetId = item.templateId || item.snippetId
        if (snippetId && String(snippetId) !== String(id)) {
          console.log(`  ${chalk.gray('Template name')}: ${snippetId}`)
        }

        if (item.description) {
          console.log(`  ${chalk.gray('Description')}: ${item.description}`)
        }

        if (item.type) {
          console.log(`  ${chalk.gray('Type')}: ${item.type}`)
        }

        if (item.codeType) {
          console.log(`  ${chalk.gray('Code Type')}: ${item.codeType}`)
        }

        if (item.appType) {
          console.log(`  ${chalk.gray('App Type')}: ${item.appType}`)
        }

        if (item.isCustom !== undefined) {
          console.log(
            `  ${chalk.gray('Custom')}: ${item.isCustom ? chalk.green('Yes') : chalk.yellow('No')}`,
          )
        }

        console.log(chalk.gray('─'.repeat(80)))
      })

      console.log(chalk.green(`\n✓ Found ${items.length} template(s)`))
      return
    }

    const rows = items.map((item) => {
      const templateIdCol = item.id || 'N/A'
      const name =
        item.name != null && String(item.name).trim() !== '' ? String(item.name) : '(no name)'
      return { templateIdCol, name }
    })

    const idHeader = 'Template ID'
    const nameHeader = 'Name'
    const idWidth = Math.max(idHeader.length, ...rows.map((r) => r.templateIdCol.length))
    const nameWidth = Math.max(nameHeader.length, ...rows.map((r) => r.name.length))

    console.log(chalk.blue(`Templates for app ${chalk.bold(appId)}:\n`))
    console.log(
      `${chalk.bold(idHeader.padEnd(idWidth))}  ${chalk.bold(nameHeader.padEnd(nameWidth))}`,
    )
    console.log(chalk.gray('─'.repeat(idWidth + 2 + nameWidth)))

    for (const { templateIdCol, name } of rows) {
      console.log(`${chalk.cyan(templateIdCol.padEnd(idWidth))}  ${name}`)
    }

    console.log(chalk.green(`\n✓ ${rows.length} item(s)`))
  } catch (error) {
    console.error(chalk.red(`Failed to list templates: ${error.message}`))
    process.exit(1)
  }
}

module.exports = libraryListCommand
