'use client'

import {
  Check,
  ExternalLink,
  Eye,
  Laptop,
  Loader2,
  type LucideIcon,
  Monitor,
  Settings2,
  Smartphone,
  Tablet,
  TriangleAlert,
} from 'lucide-react'
import type { PageStatus } from '../../lib/page-editor-service.js'
import { VIEWPORTS, type ViewportId } from './viewports.js'

export type SaveState = 'idle' | 'saving' | 'saved' | 'error'

interface EditorTopBarProps {
  title: string
  status: PageStatus
  dirty: boolean
  saveState: SaveState
  publishing: boolean
  canEdit: boolean
  canPublish: boolean
  viewport: ViewportId
  /** Breadcrumb root label + back-button text (e.g. "Pages" or "Posts"). */
  backLabel?: string
  onViewport: (v: ViewportId) => void
  onBack: () => void
  onPreview: () => void
  /**
   * Open the draft on the public site (real front-end) in a new tab. When
   * omitted the "View on site" button is hidden — e.g. for unsaved documents
   * or installs without a public URL.
   */
  onViewOnSite?: () => void
  onOpenSettings: () => void
  onSaveDraft: () => void
  onPublish: () => void
}

const VIEWPORT_ICONS: Record<string, LucideIcon> = {
  monitor: Monitor,
  laptop: Laptop,
  tablet: Tablet,
  smartphone: Smartphone,
}

const STATUS_TEXT: Record<PageStatus, { label: string; className: string }> = {
  DRAFT: { label: 'Draft', className: 'text-amber-600 dark:text-amber-400' },
  PUBLISHED: { label: 'Published', className: 'text-emerald-600 dark:text-emerald-400' },
  SCHEDULED: { label: 'Scheduled', className: 'text-amber-600 dark:text-amber-400' },
  ARCHIVED: { label: 'Archived', className: 'text-muted-foreground' },
}

export function EditorTopBar({
  title,
  status,
  dirty,
  saveState,
  publishing,
  canEdit,
  canPublish,
  viewport,
  backLabel = 'Pages',
  onViewport,
  onBack,
  onPreview,
  onViewOnSite,
  onOpenSettings,
  onSaveDraft,
  onPublish,
}: EditorTopBarProps) {
  const statusInfo = STATUS_TEXT[status]

  return (
    <header className="bg-card border-border flex h-14 shrink-0 items-center justify-between gap-4 border-b px-4">
      {/* Breadcrumb + status */}
      <div className="flex min-w-0 items-center gap-2">
        <nav aria-label="Breadcrumb" className="flex min-w-0 items-center gap-1.5 text-sm">
          <button
            type="button"
            onClick={onBack}
            className="text-muted-foreground hover:text-foreground shrink-0"
          >
            {backLabel}
          </button>
          <span className="text-muted-foreground" aria-hidden>
            /
          </span>
          <span className="text-foreground truncate font-medium">{title || 'Untitled page'}</span>
        </nav>
        <span
          className={`ml-2 shrink-0 text-xs font-medium ${statusInfo.className}`}
          aria-label={`Status: ${statusInfo.label}`}
        >
          {statusInfo.label}
        </span>
        <SaveStatus state={saveState} dirty={dirty} />
      </div>

      {/* Right controls */}
      <div className="flex items-center gap-2">
        <div
          className="border-border bg-background hidden items-center gap-0.5 rounded-lg border p-0.5 md:flex"
          role="group"
          aria-label="Preview viewport"
        >
          {VIEWPORTS.map((v) => {
            const Icon = VIEWPORT_ICONS[v.icon] ?? Monitor
            const active = v.id === viewport
            return (
              <button
                key={v.id}
                type="button"
                onClick={() => onViewport(v.id)}
                aria-pressed={active}
                title={`${v.label} (${v.width}px)`}
                className={`flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors ${
                  active
                    ? 'bg-primary text-primary-foreground'
                    : 'text-muted-foreground hover:text-foreground hover:bg-accent'
                }`}
              >
                <Icon className="h-3.5 w-3.5" aria-hidden />
                <span className="hidden lg:inline">{v.label}</span>
              </button>
            )
          })}
        </div>

        <button
          type="button"
          onClick={onOpenSettings}
          aria-label="Page settings"
          title="Page settings"
          className="text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg p-2"
        >
          <Settings2 className="h-4 w-4" aria-hidden />
        </button>

        <button
          type="button"
          onClick={onPreview}
          aria-label="Preview page"
          title="Preview page"
          className="text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg p-2"
        >
          <Eye className="h-4 w-4" aria-hidden />
        </button>

        {onViewOnSite && (
          <button
            type="button"
            onClick={onViewOnSite}
            aria-label="View draft on site"
            title="View draft on site"
            className="text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg p-2"
          >
            <ExternalLink className="h-4 w-4" aria-hidden />
          </button>
        )}

        <button
          type="button"
          onClick={onSaveDraft}
          disabled={!canEdit || saveState === 'saving' || (!dirty && saveState !== 'error')}
          className="border-border text-foreground hover:bg-accent rounded-lg border px-3 py-1.5 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"
        >
          {saveState === 'saving' ? 'Saving…' : 'Save Draft'}
        </button>

        <button
          type="button"
          onClick={onPublish}
          disabled={!canPublish || publishing || saveState === 'saving'}
          className="bg-primary text-primary-foreground hover:bg-primary/90 inline-flex items-center gap-1.5 rounded-lg px-3.5 py-1.5 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"
        >
          {publishing && <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />}
          Publish
        </button>
      </div>
    </header>
  )
}

function SaveStatus({ state, dirty }: { state: SaveState; dirty: boolean }) {
  if (state === 'saving') {
    return (
      <span
        className="text-muted-foreground ml-2 inline-flex items-center gap-1 text-xs"
        aria-live="polite"
      >
        <Loader2 className="h-3 w-3 animate-spin" aria-hidden />
        Saving…
      </span>
    )
  }
  if (state === 'error') {
    return (
      <span
        className="text-destructive ml-2 inline-flex items-center gap-1 text-xs"
        aria-live="polite"
      >
        <TriangleAlert className="h-3 w-3" aria-hidden />
        Failed to save
      </span>
    )
  }
  if (dirty) {
    return (
      <span className="text-muted-foreground ml-2 text-xs" aria-live="polite">
        Unsaved changes
      </span>
    )
  }
  if (state === 'saved') {
    return (
      <span
        className="text-muted-foreground ml-2 inline-flex items-center gap-1 text-xs"
        aria-live="polite"
      >
        <Check className="h-3 w-3" aria-hidden />
        Saved
      </span>
    )
  }
  return null
}
