'use client'

import { AlertTriangle, Loader2 } from 'lucide-react'

import { AdminThemeCard } from './AdminThemeCard.js'
import { BrandPreviewCard } from './BrandPreviewCard.js'
import { BrandingCard } from './BrandingCard.js'
import { SettingsSaveBar, SettingsValidationSummary } from './components.js'
import { TypographyMotionCard } from './TypographyMotionCard.js'
import { useAppearanceSettings } from './useAppearanceSettings.js'

export interface AppearanceTabProps {
  /** Current user's role. Only ADMIN can persist changes. */
  role?: string
  config?: Record<string, unknown>
}

function CardSkeleton() {
  return <div className="border-border bg-card h-48 animate-pulse rounded-lg border" />
}

export function AppearanceTab({ role, config }: AppearanceTabProps) {
  const canEdit = role === 'ADMIN'
  const s = useAppearanceSettings(canEdit, config)

  if (s.loading) {
    return (
      <div className="space-y-4" aria-busy="true">
        <CardSkeleton />
        <CardSkeleton />
        <CardSkeleton />
      </div>
    )
  }

  if (s.loadError) {
    return (
      <div
        role="alert"
        className="border-destructive/30 bg-destructive/10 text-destructive flex items-center justify-between gap-4 rounded-lg border p-4 text-sm"
      >
        <span className="flex items-center gap-2">
          <AlertTriangle size={16} aria-hidden="true" /> {s.loadError}
        </span>
        <button
          type="button"
          onClick={s.reload}
          className="border-destructive/40 text-destructive hover:bg-destructive/10 inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5"
        >
          <Loader2 size={14} aria-hidden="true" /> Retry
        </button>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {!canEdit && (
        <p className="text-muted-foreground border-border bg-muted rounded-lg border p-3 text-sm">
          You have read-only access to appearance settings.
        </p>
      )}

      <SettingsValidationSummary issues={s.issues} />

      <BrandingCard s={s} canEdit={canEdit} />
      <AdminThemeCard s={s} canEdit={canEdit} />
      <TypographyMotionCard s={s} canEdit={canEdit} />
      <BrandPreviewCard s={s} />

      <SettingsSaveBar
        dirty={s.dirty}
        canEdit={canEdit}
        hasErrors={s.issues.some((i) => i.severity === 'error')}
        saveState={s.saveState}
        onSave={s.save}
        onReset={s.reset}
      />
    </div>
  )
}
