import type { ComponentType, ReactNode } from 'react'
import { ArrowDownRight, ArrowUpRight, Inbox, Minus } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { cn } from '@/lib/utils'

export const dateFormat = new Intl.DateTimeFormat('en-GH', { dateStyle: 'medium', timeStyle: 'short' })
export const shortDate = new Intl.DateTimeFormat('en-GH', { day: 'numeric', month: 'short' })

const relative = new Intl.RelativeTimeFormat('en-GH', { numeric: 'auto' })
const UNITS: [Intl.RelativeTimeFormatUnit, number][] = [
  ['year', 365 * 86_400],
  ['month', 30 * 86_400],
  ['week', 7 * 86_400],
  ['day', 86_400],
  ['hour', 3_600],
  ['minute', 60],
]

// "3 hours ago", "yesterday". Falls back to "just now" under a minute.
export function timeAgo(iso: string) {
  const seconds = (new Date(iso).getTime() - Date.now()) / 1000
  for (const [unit, size] of UNITS) {
    if (Math.abs(seconds) >= size) return relative.format(Math.round(seconds / size), unit)
  }
  return 'just now'
}

const ok = 'bg-primary/10 text-primary ring-primary/20 [--dot:var(--primary)]'
const wait = 'bg-[var(--gold-glow)]/20 text-[oklch(0.45_0.1_70)] ring-[var(--gold-glow)]/40 [--dot:oklch(0.7_0.15_70)]'
const bad = 'bg-destructive/10 text-destructive ring-destructive/20 [--dot:var(--destructive)]'

const STATUS_STYLES: Record<string, { label: string; className: string; live?: boolean }> = {
  approved: { label: 'Approved', className: ok },
  sent: { label: 'Sent', className: ok },
  success: { label: 'Paid', className: ok },
  pending: { label: 'Pending', className: wait, live: true },
  partial: { label: 'Partly sent', className: wait },
  sending: { label: 'Sending', className: wait, live: true },
  scheduled: { label: 'Scheduled', className: wait },
  cancelled: { label: 'Cancelled', className: '' },
  rejected: { label: 'Rejected', className: bad },
  failed: { label: 'Failed', className: bad },
}

export function StatusBadge({ status, label, title }: { status: string; label?: string; title?: string }) {
  const entry = STATUS_STYLES[status] ?? { label: status, className: '' }
  return (
    <Badge className={cn('gap-1.5 rounded-full px-2.5 ring-1 ring-inset', entry.className)} title={title}>
      <span
        className={cn('size-1.5 rounded-full bg-[var(--dot,currentColor)]', entry.live && 'pulse-dot')}
        aria-hidden
      />
      {label ?? entry.label}
    </Badge>
  )
}

export function EmptyState({ children, icon: Icon = Inbox }: { children: ReactNode; icon?: ComponentType<{ className?: string }> }) {
  return (
    <div className="dot-grid grid justify-items-center gap-4 rounded-2xl border border-dashed bg-card/60 px-6 py-14 text-center text-muted-foreground">
      <span className="grid size-14 place-items-center rounded-2xl bg-gradient-to-br from-primary/15 to-[var(--gold-glow)]/25 text-primary ring-1 ring-primary/15">
        <Icon className="size-6" aria-hidden />
      </span>
      <p className="max-w-sm">{children}</p>
    </div>
  )
}

export function PageIntro({
  eyebrow,
  title,
  children,
  actions,
}: {
  eyebrow?: string
  title: string
  children?: ReactNode
  actions?: ReactNode
}) {
  return (
    <div className="flex flex-wrap items-end justify-between gap-4">
      <div className="grid gap-2">
        {eyebrow && (
          <p className="flex items-center gap-2 text-xs font-semibold tracking-[0.16em] text-[oklch(0.55_0.13_70)] uppercase">
            <span className="h-px w-6 bg-current" aria-hidden />
            {eyebrow}
          </p>
        )}
        <h1 className="text-3xl font-extrabold sm:text-4xl">{title}</h1>
        {children && <p className="max-w-2xl text-muted-foreground">{children}</p>}
      </div>
      {actions && <div className="flex flex-wrap gap-2">{actions}</div>}
    </div>
  )
}

// Card that holds a table. Header cells get the console's small-caps look.
export function Panel({ className, children }: { className?: string; children: ReactNode }) {
  return (
    <div
      className={cn(
        'overflow-x-auto rounded-2xl border bg-card shadow-deep',
        '[&_thead]:bg-muted/60 [&_th]:h-11 [&_th]:text-[0.7rem] [&_th]:font-semibold [&_th]:tracking-[0.08em] [&_th]:text-muted-foreground [&_th]:uppercase',
        '[&_td]:py-3 [&_tbody_tr]:transition-colors [&_tbody_tr:hover]:bg-secondary/40',
        className,
      )}
    >
      {children}
    </div>
  )
}

// Container and item classes for the status filter links at the top of a list page.
export const filterBarClass =
  'inline-flex max-w-full flex-wrap gap-1 justify-self-start rounded-xl border bg-card p-1 shadow-deep'

export function filterClass(active: boolean) {
  return cn(
    'inline-flex h-8 items-center gap-1.5 rounded-lg px-3 text-sm font-medium transition-all',
    active
      ? 'bg-gradient-to-b from-[oklch(0.42_0.09_158)] to-primary text-primary-foreground shadow-[0_6px_16px_-8px_var(--primary)]'
      : 'text-muted-foreground hover:bg-secondary hover:text-foreground',
  )
}

// Initials on a colour picked from the email, so the same customer always looks the same.
export function Avatar({ email, className }: { email: string | null | undefined; className?: string }) {
  const name = (email || '?').split('@')[0]
  const parts = name.split(/[._-]+/).filter(Boolean)
  const initials = ((parts[0]?.[0] ?? '?') + (parts[1]?.[0] ?? parts[0]?.[1] ?? '')).toUpperCase()
  let hash = 0
  for (const ch of email || '') hash = (hash * 31 + ch.charCodeAt(0)) >>> 0
  const hue = [158, 82, 40, 200, 130, 60][hash % 6]
  return (
    <span
      aria-hidden
      className={cn('grid size-8 shrink-0 place-items-center rounded-full text-[0.7rem] font-bold ring-1 ring-inset', className)}
      style={{
        background: `linear-gradient(135deg, oklch(0.9 0.07 ${hue}), oklch(0.78 0.11 ${hue}))`,
        color: `oklch(0.3 0.08 ${hue})`,
        boxShadow: `inset 0 0 0 1px oklch(0.7 0.1 ${hue} / 0.4)`,
      }}
    >
      {initials}
    </span>
  )
}

export function CustomerCell({ email, detail }: { email: string | null | undefined; detail?: ReactNode }) {
  return (
    <div className="flex min-w-0 items-center gap-3">
      <Avatar email={email} />
      <div className="min-w-0">
        <p className="max-w-56 truncate font-medium">{email || 'Unknown'}</p>
        {detail && <div className="text-xs text-muted-foreground">{detail}</div>}
      </div>
    </div>
  )
}

// Percentage change between two periods. Null when there is nothing to compare against.
export function percentChange(current: number, previous: number) {
  if (previous === 0) return current === 0 ? 0 : null
  return ((current - previous) / previous) * 100
}

export function Delta({ current, previous, className }: { current: number; previous: number; className?: string }) {
  const change = percentChange(current, previous)
  const Icon = change === null || change > 0 ? ArrowUpRight : change < 0 ? ArrowDownRight : Minus
  const tone =
    change === null || change > 0
      ? 'bg-emerald-500/15 text-emerald-700 ring-emerald-600/20'
      : change < 0
        ? 'bg-destructive/10 text-destructive ring-destructive/20'
        : 'bg-muted text-muted-foreground ring-border'
  return (
    <span
      className={cn('inline-flex items-center gap-0.5 rounded-full px-1.5 py-0.5 text-xs font-semibold ring-1 ring-inset tabular-nums', tone, className)}
      title="Compared with the 30 days before"
    >
      <Icon className="size-3" aria-hidden />
      {change === null ? 'New' : `${Math.abs(change).toFixed(change !== 0 && Math.abs(change) < 10 ? 1 : 0)}%`}
      <span className="sr-only">{change === null ? '' : change >= 0 ? ' up' : ' down'} on the previous 30 days</span>
    </span>
  )
}

// Compact row of totals shown above a list.
export function SummaryStrip({
  items,
}: {
  items: { label: string; value: string; icon: ComponentType<{ className?: string }>; tone?: 'gold' | 'red' }[]
}) {
  return (
    <dl className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
      {items.map((item) => (
        <div
          key={item.label}
          className="group relative flex items-center gap-3 overflow-hidden rounded-2xl border bg-card p-4 shadow-deep"
        >
          <span
            className={cn(
              'grid size-10 shrink-0 place-items-center rounded-xl ring-1 ring-inset',
              item.tone === 'gold'
                ? 'bg-[var(--gold-glow)]/20 text-[oklch(0.5_0.12_70)] ring-[var(--gold-glow)]/40'
                : item.tone === 'red'
                  ? 'bg-destructive/10 text-destructive ring-destructive/20'
                  : 'bg-primary/10 text-primary ring-primary/20',
            )}
          >
            <item.icon className="size-5" aria-hidden />
          </span>
          <div className="min-w-0">
            <dt className="text-xs font-medium tracking-wide text-muted-foreground uppercase">{item.label}</dt>
            <dd className="truncate font-display text-xl font-extrabold tabular-nums">{item.value}</dd>
          </div>
        </div>
      ))}
    </dl>
  )
}
