import type { ReactNode } from 'react'
import Link from 'next/link'
import { Card } from '@/libs/frontend-ui-primitives'
import type { ExplorerFeatureAction, ExplorerFeaturePage } from '@/data/explorerOperations'

export type StatusTone = 'normal' | 'warning' | 'danger'

function ActionLink({ action }: { action: ExplorerFeatureAction }) {
  const className = 'inline-flex items-center text-sm font-semibold text-primary-600 hover:underline'
  const label = `${action.label} ->`

  if (action.external) {
    return (
      <a href={action.href} className={className} target="_blank" rel="noopener noreferrer">
        {label}
      </a>
    )
  }

  return (
    <Link href={action.href} className={className}>
      {label}
    </Link>
  )
}

export function relativeAge(isoString?: string): string {
  if (!isoString) return 'Unknown'
  const parsed = Date.parse(isoString)
  if (!Number.isFinite(parsed)) return 'Unknown'
  const seconds = Math.max(0, Math.round((Date.now() - parsed) / 1000))
  if (seconds < 60) return `${seconds}s ago`
  const minutes = Math.round(seconds / 60)
  if (minutes < 60) return `${minutes}m ago`
  const hours = Math.round(minutes / 60)
  return `${hours}h ago`
}

export function formatNumber(value?: number | null): string {
  if (typeof value !== 'number' || !Number.isFinite(value)) return '0'
  return new Intl.NumberFormat('en-US').format(value)
}

export function formatCurrency(value?: number | null): string {
  if (typeof value !== 'number' || !Number.isFinite(value)) return 'Unknown'
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    maximumFractionDigits: 0,
  }).format(value)
}

export function truncateMiddle(value?: string, start = 8, end = 6): string {
  if (!value) return 'Unknown'
  if (value.length <= start + end + 3) return value
  return `${value.slice(0, start)}...${value.slice(-end)}`
}

export function StatusBadge({
  status,
  tone = 'normal',
}: {
  status: string
  tone?: StatusTone
}) {
  const toneClass =
    tone === 'danger'
      ? 'bg-red-100 text-red-700 dark:bg-red-950/40 dark:text-red-300'
      : tone === 'warning'
        ? 'bg-amber-100 text-amber-700 dark:bg-amber-950/40 dark:text-amber-300'
        : 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300'

  return (
    <span className={`inline-flex rounded-full px-2.5 py-1 text-xs font-semibold uppercase tracking-wide ${toneClass}`}>
      {status}
    </span>
  )
}

export function MetricCard({
  title,
  value,
  description,
  className,
}: {
  title: string
  value: string
  description: string
  className?: string
}) {
  return (
    <Card className={className}>
      <div className="text-sm font-semibold uppercase tracking-wide text-gray-700 dark:text-gray-300">
        {title}
      </div>
      <div className="mt-2 text-3xl font-bold text-gray-900 dark:text-white">{value}</div>
      <div className="mt-2 text-sm text-gray-600 dark:text-gray-400">{description}</div>
    </Card>
  )
}

export default function OperationsPageShell({
  page,
  children,
}: {
  page: ExplorerFeaturePage
  children: ReactNode
}) {
  return (
    <div className="container mx-auto px-4 py-6 sm:py-8">
      <div className="mb-6 max-w-4xl sm:mb-8">
        <div className="mb-3 inline-flex rounded-full border border-sky-200 bg-sky-50 px-3 py-1 text-xs font-semibold uppercase tracking-[0.2em] text-sky-700">
          {page.eyebrow}
        </div>
        <h1 className="mb-3 text-3xl font-bold text-gray-900 dark:text-white sm:text-4xl">
          {page.title}
        </h1>
        <p className="text-base leading-7 text-gray-600 dark:text-gray-400 sm:text-lg sm:leading-8">
          {page.description}
        </p>
      </div>

      {page.note ? (
        <Card className="mb-6 border border-amber-200 bg-amber-50/70 dark:border-amber-900/50 dark:bg-amber-950/20">
          <p className="text-sm leading-6 text-amber-950 dark:text-amber-100">{page.note}</p>
        </Card>
      ) : null}

      {children}

      <div className="grid gap-4 lg:grid-cols-2">
        {page.actions.map((action) => (
          <Card key={`${action.title}-${action.href}`} className="border border-gray-200 dark:border-gray-700">
            <div className="flex h-full flex-col">
              <div className="text-base font-semibold text-gray-900 dark:text-white">{action.title}</div>
              <p className="mt-2 flex-1 text-sm leading-6 text-gray-600 dark:text-gray-400">
                {action.description}
              </p>
              <div className="mt-4">
                <ActionLink action={action} />
              </div>
            </div>
          </Card>
        ))}
      </div>
    </div>
  )
}
