'use client'

import * as React from 'react'
import { formatDistanceToNow } from 'date-fns'
import { Eye, TerminalSquare } from 'lucide-react'
import { cn } from '../../lib/utils'
import { SessionStatusBadge } from './SessionStatusBadge'
import type { SessionSummary } from './types'

export interface SessionCardProps {
  session: SessionSummary
  /** Inject routing: return an href for the session detail. Renders the title as a link. */
  href?: (id: string) => string
  /** Called when the card / Details is activated (used when `href` is absent). */
  onOpen?: (id: string) => void
  /** Called when the Terminal action is activated. */
  onOpenTerminal?: (id: string) => void
  className?: string
}

/** Relative "created …" label, tolerant of string | number timestamps. */
export function formatRelative(value: string | number): string {
  const date = typeof value === 'number' ? new Date(value) : new Date(value)
  if (Number.isNaN(date.getTime())) return String(value)
  return formatDistanceToNow(date, { addSuffix: true })
}

function SessionCardComponent({ session, href, onOpen, onOpenTerminal, className }: SessionCardProps) {
  const open = React.useCallback(() => onOpen?.(session.id), [onOpen, session.id])

  const handleKeyDown = React.useCallback(
    (e: React.KeyboardEvent) => {
      if (href) return // native link handles keyboard
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault()
        open()
      }
    },
    [href, open],
  )

  const titleNode = href ? (
    <a
      href={href(session.id)}
      className="truncate text-lg font-semibold text-foreground hover:text-primary"
      title={session.name}
    >
      {session.name}
    </a>
  ) : (
    <h3 className="truncate text-lg font-semibold text-foreground" title={session.name}>
      {session.name}
    </h3>
  )

  const clickable = !href && !!onOpen

  return (
    <div
      data-testid="session-card"
      role={clickable ? 'button' : undefined}
      tabIndex={clickable ? 0 : undefined}
      onClick={clickable ? open : undefined}
      onKeyDown={clickable ? handleKeyDown : undefined}
      aria-label={clickable ? `Open session ${session.name}` : undefined}
      className={cn(
        'relative rounded-lg border border-border bg-card p-4 transition-colors',
        clickable && 'cursor-pointer hover:border-primary/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
        className,
      )}
    >
      {session.hasUnread && (
        <span
          data-testid="session-card-unread"
          aria-label="Has unread activity"
          className="absolute right-4 top-4 h-2 w-2 rounded-full bg-primary"
        />
      )}

      <div className="flex items-start gap-4">
        {session.number != null && (
          <div className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-lg border border-border bg-muted">
            <span className="font-mono text-sm font-semibold text-muted-foreground">
              {String(session.number).padStart(3, '0')}
            </span>
          </div>
        )}

        <div className="min-w-0 flex-1">
          <div className="mb-2 flex items-start justify-between gap-2">
            {titleNode}
            <SessionStatusBadge status={session.status} label={session.statusLabel} isActive={session.isActive} />
          </div>

          <div className="space-y-1 text-sm text-muted-foreground">
            {session.agentName && (
              <div className="flex items-center gap-2">
                <span className="text-muted-foreground/70">Agent:</span>
                <span className="truncate text-foreground" title={session.agentName}>
                  {session.agentName}
                </span>
              </div>
            )}
            {session.projectName && (
              <div className="flex items-center gap-2">
                <span className="text-muted-foreground/70">Project:</span>
                <span className="truncate text-foreground" title={session.projectName}>
                  {session.projectName}
                </span>
              </div>
            )}
            {session.branch && (
              <div className="flex items-center gap-2">
                <span className="text-muted-foreground/70">Branch:</span>
                <span className="truncate font-mono text-xs text-foreground" title={session.branch}>
                  {session.branch}
                </span>
              </div>
            )}
            <div className="text-xs text-muted-foreground/70">Created {formatRelative(session.createdAt)}</div>
          </div>

          {(onOpen || href || onOpenTerminal) && (
            <div className="mt-4 flex gap-2 border-t border-border pt-4">
              {href ? (
                <a
                  href={href(session.id)}
                  onClick={(e) => e.stopPropagation()}
                  className="inline-flex flex-1 items-center justify-center gap-1 rounded-md border border-border px-3 py-1.5 text-sm text-foreground transition-colors hover:bg-accent"
                >
                  <Eye className="h-4 w-4" aria-hidden="true" />
                  Details
                </a>
              ) : (
                onOpen && (
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation()
                      open()
                    }}
                    className="inline-flex flex-1 items-center justify-center gap-1 rounded-md border border-border px-3 py-1.5 text-sm text-foreground transition-colors hover:bg-accent"
                  >
                    <Eye className="h-4 w-4" aria-hidden="true" />
                    Details
                  </button>
                )
              )}
              {onOpenTerminal && (
                <button
                  type="button"
                  onClick={(e) => {
                    e.stopPropagation()
                    onOpenTerminal(session.id)
                  }}
                  className="inline-flex flex-1 items-center justify-center gap-1 rounded-md border border-border px-3 py-1.5 text-sm text-foreground transition-colors hover:bg-accent"
                >
                  <TerminalSquare className="h-4 w-4" aria-hidden="true" />
                  Terminal
                </button>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

/** Memoised — cheap re-renders in long lists. */
export const SessionCard = React.memo(SessionCardComponent)

/** Skeleton loader matching the card layout. */
export function SessionCardSkeleton({ className }: { className?: string }) {
  return (
    <div className={cn('rounded-lg border border-border bg-card p-4', className)}>
      <div className="flex items-start gap-4">
        <div className="h-12 w-12 flex-shrink-0 animate-pulse rounded-lg bg-muted" />
        <div className="flex-1 space-y-3">
          <div className="h-6 w-3/4 animate-pulse rounded bg-muted" />
          <div className="space-y-2">
            <div className="h-4 w-full animate-pulse rounded bg-muted" />
            <div className="h-4 w-5/6 animate-pulse rounded bg-muted" />
            <div className="h-4 w-4/6 animate-pulse rounded bg-muted" />
          </div>
          <div className="flex gap-2 border-t border-border pt-4">
            <div className="h-9 flex-1 animate-pulse rounded bg-muted" />
            <div className="h-9 flex-1 animate-pulse rounded bg-muted" />
          </div>
        </div>
      </div>
    </div>
  )
}
