import { useTranslation } from 'react-i18next'
import { Link } from '@tanstack/react-router'
import { ClipboardList, FileText } from 'lucide-react'
import type { DictionaryDetail } from '@/api/client'
import { cn } from '@/lib/utils'

/**
 * WorkflowBanner — status banner для editor (Screen 2 per handoff).
 *
 * <p>Backend не имеет explicit dict-level workflow state (draft → review →
 * live transition). Используем существующие поля как proxy:
 * <ul>
 *   <li><b>Live</b> (default) — approvalRequired=false → published immediately.
 *       Постоянный "Опубликовано" banner = noise (статус уже виден в InfoPanel
 *       version/updatedAt). Поэтому возвращаем null — banner показываем только
 *       когда есть actionable state.</li>
 *   <li><b>Review pending</b> — approvalRequired=true И есть pending drafts
 *       (pendingCount > 0). Warn-bg, link to /reviews.</li>
 *   <li><b>Approval enabled empty</b> — approvalRequired=true но нет drafts.
 *       Accent-bg, informational "changes require review".</li>
 * </ul>
 *
 * <p>Когда backend добавит explicit workflowState (draft/review/live transition
 * на dict-level) — расширим этот компонент. Сейчас фокус UI на approval flow.
 */

export type WorkflowBannerProps = {
  detail: DictionaryDetail
  /** Pending drafts count для this dict (из useDictPendingDrafts). */
  pendingCount?: number
}

export function WorkflowBanner({ detail, pendingCount = 0 }: WorkflowBannerProps) {
  const { t } = useTranslation()

  // === Case 1: Live — no approval required ===
  // Постоянный "Опубликовано" banner = шум. Status уже виден в InfoPanel
  // (scope, version, updatedAt). Не показываем banner вообще.
  if (!detail.approvalRequired) {
    return null
  }

  // === Case 2: Review pending — approval required + drafts queued ===
  if (pendingCount > 0) {
    return (
      <Banner
        variant="review"
        icon={<ClipboardList size={16} strokeWidth={2} className="shrink-0" />}
        action={
          <Link
            to="/reviews"
            className="text-body font-medium text-accent hover:underline shrink-0"
          >
            {t('workflow.review.open', { defaultValue: 'Открыть /reviews' })} →
          </Link>
        }
      >
        <span className="font-medium">
          {t('workflow.review.title', {
            count: pendingCount,
            defaultValue: 'На ревью {{count}}',
          })}
        </span>
        <span className="text-cell opacity-70">
          {t('workflow.review.subtitle', {
            defaultValue: 'правки записей ждут approval',
          })}
        </span>
      </Banner>
    )
  }

  // === Case 3: Approval enabled, no pending ===
  return (
    <Banner
      variant="info"
      icon={<FileText size={16} strokeWidth={2} className="shrink-0" />}
    >
      <span className="font-medium">
        {t('workflow.approval.title', { defaultValue: 'Approval workflow' })}
      </span>
      <span className="text-cell opacity-70">
        {t('workflow.approval.subtitle', {
          defaultValue: 'правки записей требуют ревью',
        })}
      </span>
    </Banner>
  )
}

type BannerProps = {
  variant: 'live' | 'review' | 'info' | 'draft'
  icon: React.ReactNode
  action?: React.ReactNode
  children: React.ReactNode
}

const VARIANT_CLASS: Record<BannerProps['variant'], string> = {
  live: 'bg-green-bg border-l-green text-ink',
  review: 'bg-warn-bg border-l-warn text-ink',
  info: 'bg-accent-bg border-l-accent text-ink',
  draft: 'bg-warn-bg border-l-warn text-ink',
}

function Banner({ variant, icon, action, children }: BannerProps) {
  return (
    <div
      role="status"
      className={cn(
        'flex items-center gap-3 px-4 py-2.5 rounded-md border-l-4 text-body',
        VARIANT_CLASS[variant],
      )}
    >
      {icon}
      <div className="flex items-center gap-2 flex-wrap min-w-0 flex-1">
        {children}
      </div>
      {action}
    </div>
  )
}
