interface DiscordEmbed {
  title?: string
  description?: string
  color?: number
  fields?: { name: string; value: string; inline?: boolean }[]
  timestamp?: string
  footer?: { text: string; icon_url?: string }
  thumbnail?: { url: string }
  author?: { name: string; icon_url?: string; url?: string }
}

interface DiscordWebhookPayload {
  content?: string
  username?: string
  avatar_url?: string
  embeds?: DiscordEmbed[]
}

const COLORS = {
  info: 0x3b82f6,     // blue
  success: 0x22c55e,  // green
  warning: 0xf59e0b,  // amber
  error: 0xef4444,    // red
  auth: 0x5865f2,     // discord blurple
  admin: 0x8b5cf6,    // purple
  update: 0x06b6d4,   // cyan
  maintenance: 0xf97316, // orange
}

export type LogCategory = 
  | 'auth'
  | 'admin'
  | 'settings'
  | 'error'
  | 'installation'
  | 'demo'
  | 'maintenance'
  | 'update'
  | 'panelBuilder'
  | 'branding'
  | 'domain'

export async function sendDiscordLog(
  category: LogCategory,
  title: string,
  description: string,
  fields?: { name: string; value: string; inline?: boolean }[],
  webhookUrl?: string
): Promise<boolean> {
  const url = webhookUrl || process.env.DISCORD_WEBHOOK_URL
  
  if (!url) {
    console.log('[Discord Webhook] No webhook URL configured, skipping log')
    return false
  }

  const colorMap: Record<LogCategory, number> = {
    auth: COLORS.auth,
    admin: COLORS.admin,
    settings: COLORS.info,
    error: COLORS.error,
    installation: COLORS.success,
    demo: COLORS.warning,
    maintenance: COLORS.maintenance,
    update: COLORS.update,
    panelBuilder: COLORS.info,
    branding: COLORS.info,
    domain: COLORS.info,
  }

  const payload: DiscordWebhookPayload = {
    username: 'SKG UCP',
    embeds: [
      {
        title: `[${category.toUpperCase()}] ${title}`,
        description,
        color: colorMap[category] || COLORS.info,
        fields,
        timestamp: new Date().toISOString(),
        footer: {
          text: 'SKG UCP Logging System',
        },
      },
    ],
  }

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    })

    if (!response.ok) {
      console.error('[Discord Webhook] Failed to send log:', response.status)
      return false
    }

    return true
  } catch (error) {
    console.error('[Discord Webhook] Error sending log:', error)
    return false
  }
}

export async function testWebhook(webhookUrl: string): Promise<{ success: boolean; error?: string }> {
  if (!webhookUrl) {
    return { success: false, error: 'No webhook URL provided' }
  }

  // Validate URL format
  if (!webhookUrl.startsWith('https://discord.com/api/webhooks/') && 
      !webhookUrl.startsWith('https://discordapp.com/api/webhooks/')) {
    return { success: false, error: 'Invalid Discord webhook URL format' }
  }

  const payload: DiscordWebhookPayload = {
    username: 'SKG UCP',
    embeds: [
      {
        title: 'Webhook Test Successful',
        description: 'Your Discord webhook is configured correctly and ready to receive logs from SKG UCP.',
        color: COLORS.success,
        timestamp: new Date().toISOString(),
        footer: {
          text: 'SKG UCP Installation Test',
        },
      },
    ],
  }

  try {
    const response = await fetch(webhookUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    })

    if (!response.ok) {
      const text = await response.text()
      return { success: false, error: `Webhook returned ${response.status}: ${text}` }
    }

    return { success: true }
  } catch (error) {
    return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }
  }
}
