import { useI18n } from '../../i18n/useI18n'

export interface ProgressData {
  status: string      // running | completed | error
  current_step: string
  completed_steps: number
  total_steps: number
  error_message?: string | null
}

export interface AllProgress {
  analysis: ProgressData | null
  reference_image_generation: ProgressData | null
  image_generation: ProgressData | null
  webbook: ProgressData | null
  pdf_render: ProgressData | null
}

const PIPELINE_STAGES = ['analysis', 'reference_image_generation', 'image_generation', 'webbook', 'pdf_render'] as const

/**
 * Compact progress bar for episode cards (Episodes.tsx).
 */
export function ProgressBar({ data }: { data: ProgressData }) {
  const pct = data.total_steps > 0
    ? Math.round(data.completed_steps / data.total_steps * 100)
    : 0

  const fillClass =
    data.status === 'completed' ? 'completed' :
    data.status === 'error' ? 'error' : ''

  return (
    <div style={{ minWidth: '140px' }}>
      <div className="progress-bar">
        <div
          className={`progress-fill ${fillClass}`}
          style={{ width: `${data.status === 'completed' ? 100 : pct}%` }}
        />
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '4px' }}>
        <span style={{
          fontSize: '11px',
          color: data.status === 'error' ? 'var(--red)' : 'var(--text-muted)',
          maxWidth: '200px',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap',
        }}>
          {data.status === 'error'
            ? (data.error_message || 'Error')
            : data.current_step}
        </span>
        <span style={{ fontSize: '11px', color: 'var(--text-dim)', flexShrink: 0, marginLeft: '8px' }}>
          {data.status === 'completed' ? '100%' : `${pct}%`}
        </span>
      </div>
    </div>
  )
}

/**
 * Stage indicator icon/badge for pipeline panel.
 */
function StageIndicator({ status }: { status: string | null }) {
  if (!status) {
    // pending
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        width: '20px', height: '20px', borderRadius: '50%',
        background: 'var(--bg-input)', border: '1px solid var(--border)',
        fontSize: '10px', color: 'var(--text-dim)',
      }}>
        -
      </span>
    )
  }
  if (status === 'completed') {
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        width: '20px', height: '20px', borderRadius: '50%',
        background: 'var(--green-bg)', color: 'var(--green)',
        fontSize: '12px', fontWeight: 700,
      }}>
        {'\u2713'}
      </span>
    )
  }
  if (status === 'error') {
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        width: '20px', height: '20px', borderRadius: '50%',
        background: 'var(--red-bg)', color: 'var(--red)',
        fontSize: '12px', fontWeight: 700,
      }}>
        !
      </span>
    )
  }
  // running
  return (
    <span className="badge pulse" style={{
      width: '20px', height: '20px', borderRadius: '50%',
      padding: 0, display: 'inline-flex', alignItems: 'center',
      justifyContent: 'center', fontSize: '10px',
    }}>
      {'\u25CF'}
    </span>
  )
}

/**
 * Full pipeline progress panel for EpisodeDetail.tsx.
 * Shows all 4 stages with progress bars.
 */
export function PipelineProgressPanel({ progress }: { progress: AllProgress }) {
  const { t } = useI18n()

  const stageLabels: Record<string, string> = {
    analysis: t('progress.analysis'),
    reference_image_generation: t('progress.reference_image_generation'),
    image_generation: t('progress.image_generation'),
    webbook: t('progress.webbook'),
    pdf_render: t('progress.pdf_render'),
  }

  const statusLabel = (status: string | null): string => {
    if (!status) return t('progress.pending')
    const map: Record<string, string> = {
      running: t('progress.running'),
      completed: t('progress.completed'),
      error: t('progress.error'),
    }
    return map[status] ?? status
  }

  return (
    <div style={{
      background: 'var(--bg-card)',
      border: '1px solid var(--border)',
      borderRadius: 'var(--radius)',
      padding: '16px 20px',
    }}>
      <div style={{
        fontSize: '12px',
        fontWeight: 700,
        color: 'var(--text-dim)',
        textTransform: 'uppercase',
        letterSpacing: '0.06em',
        marginBottom: '12px',
      }}>
        {t('progress.pipeline')}
      </div>
      <div style={{ display: 'grid', gap: '10px' }}>
        {PIPELINE_STAGES.map((stage) => {
          const data = progress[stage]
          return (
            <div key={stage} style={{
              display: 'flex',
              alignItems: 'center',
              gap: '10px',
              padding: '8px 12px',
              background: 'var(--bg-raised)',
              borderRadius: 'var(--radius-sm)',
            }}>
              <StageIndicator status={data?.status ?? null} />
              <div style={{
                fontSize: '13px',
                fontWeight: 600,
                minWidth: '80px',
              }}>
                {stageLabels[stage]}
              </div>
              <div style={{ flex: 1 }}>
                {data && data.status === 'running' ? (
                  <ProgressBar data={data} />
                ) : (
                  <span style={{
                    fontSize: '11px',
                    color: data?.status === 'error' ? 'var(--red)' : 'var(--text-dim)',
                  }}>
                    {statusLabel(data?.status ?? null)}
                  </span>
                )}
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}
