'use client'

import {
  AlertTriangle,
  ChevronDown,
  ChevronRight,
  ImageIcon,
  Loader2,
  Trash2,
  Upload,
} from 'lucide-react'
import { useRef } from 'react'

import type { BrandAssetField, UseAppearanceSettings } from './useAppearanceSettings.js'

const LOGO_ACCEPT = 'image/svg+xml,image/png'

function previewSurface(dark: boolean): string {
  return dark ? 'bg-foreground border-border' : 'bg-muted border-border'
}

function LogoField({
  label,
  helper,
  field,
  accept,
  square,
  darkSurface,
  brand,
  assets,
  uploadingField,
  canEdit,
  warning,
  onUpload,
  onRemove,
}: {
  label: string
  helper: string
  field: BrandAssetField
  accept: string
  square?: boolean
  darkSurface?: boolean
  brand: UseAppearanceSettings['brand']
  assets: UseAppearanceSettings['assets']
  uploadingField: BrandAssetField | null
  canEdit: boolean
  warning?: string
  onUpload: (field: BrandAssetField, file: File) => void
  onRemove: (field: BrandAssetField) => void
}) {
  const inputRef = useRef<HTMLInputElement>(null)
  const assetId = brand[field]
  const asset = assetId ? assets[assetId] : undefined
  const uploading = uploadingField === field
  const inputId = `brand-${field}`

  return (
    <div className="flex items-start gap-4">
      <div
        className={`flex shrink-0 items-center justify-center overflow-hidden rounded-md border p-2 ${previewSurface(
          Boolean(darkSurface),
        )} ${square ? 'h-12 w-12' : 'h-12 w-20'}`}
        aria-hidden={!asset}
      >
        {asset?.url ? (
          // Never stretch/crop — contain preserves aspect ratio + transparency.
          <img
            src={asset.url}
            alt={`${label} preview`}
            className="max-h-full max-w-full object-contain"
          />
        ) : (
          <ImageIcon size={18} className="text-muted-foreground" aria-hidden="true" />
        )}
      </div>

      <div className="min-w-0 flex-1">
        <label htmlFor={inputId} className="text-foreground block text-base font-medium">
          {label}
        </label>
        <p className="text-muted-foreground mt-0.5 text-sm">{helper}</p>

        <div className="mt-2 flex items-center gap-2">
          <input
            ref={inputRef}
            id={inputId}
            type="file"
            accept={accept}
            className="sr-only"
            disabled={!canEdit || uploading}
            onChange={(e) => {
              const file = e.target.files?.[0]
              if (file) onUpload(field, file)
              if (inputRef.current) inputRef.current.value = ''
            }}
          />
          <button
            type="button"
            onClick={() => inputRef.current?.click()}
            disabled={!canEdit || uploading}
            className="border-border text-foreground hover:bg-accent inline-flex items-center gap-2 rounded-md border px-3 py-1.5 text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50"
          >
            {uploading ? (
              <Loader2 size={14} className="animate-spin" aria-hidden="true" />
            ) : (
              <Upload size={14} aria-hidden="true" />
            )}
            {asset ? 'Replace' : `Upload ${label.toLowerCase()}`}
          </button>
          {asset && (
            <button
              type="button"
              onClick={() => onRemove(field)}
              disabled={!canEdit}
              className="text-muted-foreground hover:text-destructive inline-flex items-center gap-1.5 rounded-md px-2 py-1.5 text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50"
              aria-label={`Remove ${label}`}
            >
              <Trash2 size={14} aria-hidden="true" /> Remove
            </button>
          )}
        </div>

        {warning && (
          <p
            className="text-warning mt-2 flex items-start gap-1.5 text-sm"
            role="status"
            aria-live="polite"
          >
            <AlertTriangle size={14} className="mt-0.5 shrink-0" aria-hidden="true" /> {warning}
          </p>
        )}
      </div>
    </div>
  )
}

export function BrandingCard({ s, canEdit }: { s: UseAppearanceSettings; canEdit: boolean }) {
  const warningFor = (field: BrandAssetField): string | undefined =>
    s.issues.find((i) => i.field === field && i.severity === 'warning')?.message

  const custom = s.brand.mode === 'customAdminBrand'

  return (
    <section className="border-border bg-card rounded-lg border p-6">
      <header className="mb-4">
        <h3 className="text-foreground text-lg font-medium">Branding</h3>
        <p className="text-muted-foreground mt-0.5 text-sm">
          Logos shown in the admin sidebar and on the public site.
        </p>
      </header>

      <div className="space-y-5">
        <LogoField
          label="Primary Logo"
          helper="SVG or PNG, up to 1MB. Best for the public header and full admin sidebar."
          field="publicPrimaryLogoAssetId"
          accept={LOGO_ACCEPT}
          brand={s.brand}
          assets={s.assets}
          uploadingField={s.uploadingField}
          canEdit={canEdit}
          warning={warningFor('publicPrimaryLogoAssetId')}
          onUpload={s.uploadAsset}
          onRemove={s.removeAsset}
        />

        <LogoField
          label="Favicon / App Icon Source"
          helper="32×32 PNG or SVG. A larger square image is fine — it scales down cleanly."
          field="faviconSourceAssetId"
          accept={LOGO_ACCEPT}
          square
          brand={s.brand}
          assets={s.assets}
          uploadingField={s.uploadingField}
          canEdit={canEdit}
          warning={warningFor('faviconSourceAssetId')}
          onUpload={s.uploadAsset}
          onRemove={s.removeAsset}
        />

        {/* Advanced logo variants disclosure (Logo Mark + Dark Mode Logo). */}
        <div className="border-border border-t pt-4">
          <button
            type="button"
            onClick={() => s.setShowAdvanced(!s.showAdvanced)}
            aria-expanded={s.showAdvanced}
            className="text-foreground hover:text-brand inline-flex items-center gap-1.5 text-sm font-medium transition-colors"
          >
            {s.showAdvanced ? (
              <ChevronDown size={16} aria-hidden="true" />
            ) : (
              <ChevronRight size={16} aria-hidden="true" />
            )}
            Advanced logo variants
          </button>

          {s.showAdvanced && (
            <div className="mt-4 space-y-5">
              <LogoField
                label="Logo Mark"
                helper="Square icon or mark. Used for the collapsed sidebar, compact UI, and app icons."
                field="publicLogoMarkAssetId"
                accept={LOGO_ACCEPT}
                square
                brand={s.brand}
                assets={s.assets}
                uploadingField={s.uploadingField}
                canEdit={canEdit}
                warning={warningFor('publicLogoMarkAssetId')}
                onUpload={s.uploadAsset}
                onRemove={s.removeAsset}
              />
              <LogoField
                label="Dark Mode Logo"
                helper="Optional. Used on dark backgrounds or the dark admin theme."
                field="publicDarkLogoAssetId"
                accept={LOGO_ACCEPT}
                darkSurface
                brand={s.brand}
                assets={s.assets}
                uploadingField={s.uploadingField}
                canEdit={canEdit}
                warning={warningFor('publicDarkLogoAssetId')}
                onUpload={s.uploadAsset}
                onRemove={s.removeAsset}
              />
            </div>
          )}
        </div>

        {/* Admin branding mode — admin inherits the public brand by default. */}
        <div className="border-border border-t pt-4">
          <div className="flex items-center gap-2">
            <span className="text-foreground text-base font-medium">Admin branding</span>
          </div>
          <p className="text-muted-foreground mt-0.5 text-sm">
            Admin uses the public brand by default.
          </p>
          <div
            role="radiogroup"
            aria-label="Admin branding mode"
            className="border-border bg-muted mt-2 inline-flex rounded-md border p-0.5"
          >
            {(
              [
                ['inheritPublicBrand', 'Inherit public brand'],
                ['customAdminBrand', 'Custom admin logo'],
              ] as const
            ).map(([value, text]) => {
              const active = s.brand.mode === value
              return (
                <button
                  key={value}
                  type="button"
                  role="radio"
                  aria-checked={active}
                  disabled={!canEdit}
                  onClick={() => s.setBrandingMode(value)}
                  className={`rounded px-3 py-1.5 text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
                    active
                      ? 'bg-card text-foreground shadow-sm'
                      : 'text-muted-foreground hover:text-foreground'
                  }`}
                >
                  {text}
                </button>
              )
            })}
          </div>

          {custom && (
            <div className="mt-4 space-y-5">
              <LogoField
                label="Admin Primary Logo"
                helper="Shown in the admin sidebar instead of the public logo."
                field="adminPrimaryLogoAssetId"
                accept={LOGO_ACCEPT}
                brand={s.brand}
                assets={s.assets}
                uploadingField={s.uploadingField}
                canEdit={canEdit}
                warning={warningFor('adminPrimaryLogoAssetId')}
                onUpload={s.uploadAsset}
                onRemove={s.removeAsset}
              />
              <LogoField
                label="Admin Logo Mark"
                helper="Square mark for the collapsed admin sidebar."
                field="adminLogoMarkAssetId"
                accept={LOGO_ACCEPT}
                square
                brand={s.brand}
                assets={s.assets}
                uploadingField={s.uploadingField}
                canEdit={canEdit}
                warning={warningFor('adminLogoMarkAssetId')}
                onUpload={s.uploadAsset}
                onRemove={s.removeAsset}
              />
            </div>
          )}
        </div>

        {/* Default alt text */}
        <div className="border-border border-t pt-4">
          <label htmlFor="brand-alt" className="text-foreground block text-base font-medium">
            Logo alt text
          </label>
          <p className="text-muted-foreground mt-0.5 mb-2 text-sm">
            Used by screen readers on the public site. Defaults to the Site Title when empty.
          </p>
          <input
            id="brand-alt"
            type="text"
            value={s.brand.defaultLogoAltText ?? ''}
            disabled={!canEdit}
            onChange={(e) => s.setAltText(e.target.value)}
            placeholder="Site Title"
            className="border-border bg-input-background text-foreground focus-visible:ring-ring w-full max-w-md rounded-md border px-3 py-2 text-base focus-visible:ring-2 focus-visible:outline-none disabled:opacity-50"
          />
        </div>
      </div>

      {s.saveError && (
        <p className="text-destructive mt-4 text-sm" role="alert">
          {s.saveError}
        </p>
      )}
    </section>
  )
}
