'use client'

import { AlertTriangle, Layers, Loader2, RefreshCw } from 'lucide-react'
import { useApiData } from '../../lib/useApiData.js'

interface PageTemplate {
  id: string
  name?: string
  description?: string | null
  category?: string
  builtIn?: boolean
  updatedAt?: string
}

export interface PageTemplatesProps {
  onNavigate?: (path: string) => void
}

export function PageTemplates({ onNavigate }: PageTemplatesProps) {
  const { data, loading, error, refetch } = useApiData<PageTemplate[]>('/page-templates')
  const templates = data ?? []

  if (loading) {
    return (
      <div className="flex h-64 items-center justify-center p-4" role="status" aria-live="polite">
        <Loader2 className="text-primary h-6 w-6 animate-spin" />
        <span className="sr-only">Loading page templates</span>
      </div>
    )
  }

  return (
    <div className="p-4 pr-8">
      {error && (
        <div className="border-border bg-card mb-4 flex items-center gap-3 rounded-lg border p-3">
          <AlertTriangle className="text-muted-foreground h-5 w-5 shrink-0" />
          <span className="text-foreground flex-1 text-sm">{error}</span>
          <button
            type="button"
            onClick={refetch}
            className="border-border text-foreground hover:bg-accent rounded-md border px-3 py-1 text-sm"
          >
            Retry
          </button>
        </div>
      )}

      <div className="mb-4 flex items-center justify-between">
        <div>
          <h1 className="text-foreground mb-1 text-2xl font-medium">Page Templates</h1>
          <p className="text-muted-foreground text-sm">
            {templates.length} saved template{templates.length === 1 ? '' : 's'}
          </p>
        </div>
        <button
          type="button"
          onClick={refetch}
          className="border-border text-foreground hover:bg-accent inline-flex items-center gap-2 rounded-md border px-3 py-2 text-sm font-medium"
        >
          <RefreshCw className="h-4 w-4" />
          Refresh
        </button>
      </div>

      {templates.length === 0 ? (
        <div className="border-border bg-card rounded-lg border p-8 text-center">
          <Layers className="text-muted-foreground mx-auto mb-3 h-8 w-8" />
          <h2 className="text-foreground mb-1 text-lg font-medium">No page templates yet</h2>
          <p className="text-muted-foreground mb-4 text-sm">
            Built-in templates are seeded by the CMS when the templates API is available.
          </p>
          <button
            type="button"
            onClick={() => onNavigate?.('/saved-sections')}
            className="bg-primary text-primary-foreground rounded-md px-4 py-2 text-sm font-medium hover:opacity-90"
          >
            View Saved Sections
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
          {templates.map((template) => (
            <div key={template.id} className="border-border bg-card rounded-lg border p-4">
              <div className="mb-3 flex items-start justify-between gap-3">
                <div>
                  <h2 className="text-foreground text-base font-medium">
                    {template.name ?? 'Untitled template'}
                  </h2>
                  <p className="text-muted-foreground mt-1 text-sm">
                    {template.description ?? 'No description provided.'}
                  </p>
                </div>
                {template.builtIn && (
                  <span className="bg-muted text-muted-foreground rounded-full px-2 py-0.5 text-xs">
                    Built-in
                  </span>
                )}
              </div>
              <div className="text-muted-foreground flex items-center justify-between text-sm">
                <span>{template.category ?? 'content'}</span>
                <span>
                  {template.updatedAt ? new Date(template.updatedAt).toLocaleDateString() : ''}
                </span>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
