import React, { useState, useEffect } from 'react'

export default function ArtworkActions({ artwork, canonicalUrl, mobilePriority = false, onStatsChange }) {
  const [liked, setLiked] = useState(Boolean(artwork?.viewer?.is_liked))
  const [favorited, setFavorited] = useState(Boolean(artwork?.viewer?.is_favorited))
  const [reporting, setReporting] = useState(false)
  const [downloading, setDownloading] = useState(false)
  // Fallback URL used only if the API call fails entirely
  const fallbackUrl = artwork?.thumbs?.xl?.url || artwork?.thumbs?.lg?.url || artwork?.file?.url || '#'
  const shareUrl = canonicalUrl || artwork?.canonical_url || (typeof window !== 'undefined' ? window.location.href : '#')
  const csrfToken = typeof document !== 'undefined'
    ? document.querySelector('meta[name="csrf-token"]')?.getAttribute('content')
    : null

  // Track the view once per browser session (sessionStorage prevents re-firing).
  useEffect(() => {
    if (!artwork?.id) return
    const key = `sb_viewed_${artwork.id}`
    if (typeof sessionStorage !== 'undefined' && sessionStorage.getItem(key)) return
    fetch(`/api/art/${artwork.id}/view`, {
      method: 'POST',
      headers: { 'X-CSRF-TOKEN': csrfToken || '', 'Content-Type': 'application/json' },
      credentials: 'same-origin',
    }).then(res => {
      // Only mark as seen after a confirmed success — if the POST fails the
      // next page load will retry rather than silently skipping forever.
      if (res.ok && typeof sessionStorage !== 'undefined') {
        sessionStorage.setItem(key, '1')
      }
    }).catch(() => {})
  }, [artwork?.id]) // eslint-disable-line react-hooks/exhaustive-deps

  /**
   * Async download handler:
   * 1. POST /api/art/{id}/download  → records the event, returns { url, filename }
   * 2. Programmatically clicks a hidden <a download="filename"> to trigger the save dialog
   * 3. Falls back to the pre-resolved fallbackUrl if the API is unreachable
   */
  const handleDownload = async (e) => {
    e.preventDefault()
    if (downloading || !artwork?.id) return
    setDownloading(true)
    try {
      const res = await fetch(`/api/art/${artwork.id}/download`, {
        method: 'POST',
        headers: { 'X-CSRF-TOKEN': csrfToken || '', 'Content-Type': 'application/json' },
        credentials: 'same-origin',
      })
      const data = res.ok ? await res.json() : null
      const url      = data?.url      || fallbackUrl
      const filename = data?.filename || ''

      // Trigger browser save-dialog with the correct filename
      const a = document.createElement('a')
      a.href = url
      a.download = filename
      a.rel = 'noopener noreferrer'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    } catch {
      // API unreachable — open the best available URL directly
      window.open(fallbackUrl, '_blank', 'noopener,noreferrer')
    } finally {
      setDownloading(false)
    }
  }

  const postInteraction = async (url, body) => {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': csrfToken || '',
      },
      credentials: 'same-origin',
      body: JSON.stringify(body),
    })

    if (!response.ok) throw new Error('Request failed')
    return response.json()
  }

  const onToggleLike = async () => {
    const nextState = !liked
    setLiked(nextState)
    try {
      await postInteraction(`/api/artworks/${artwork.id}/like`, { state: nextState })
      onStatsChange?.({ likes: nextState ? 1 : -1 })
    } catch {
      setLiked(!nextState)
    }
  }

  const onToggleFavorite = async () => {
    const nextState = !favorited
    setFavorited(nextState)
    try {
      await postInteraction(`/api/artworks/${artwork.id}/favorite`, { state: nextState })
      onStatsChange?.({ favorites: nextState ? 1 : -1 })
    } catch {
      setFavorited(!nextState)
    }
  }

  const onShare = async () => {
    try {
      if (navigator.share) {
        await navigator.share({
          title: artwork?.title || 'Artwork',
          url: shareUrl,
        })
        return
      }

      await navigator.clipboard.writeText(shareUrl)
    } catch {
      // noop
    }
  }

  const onReport = async () => {
    if (reporting) return
    setReporting(true)
    try {
      await postInteraction(`/api/artworks/${artwork.id}/report`, {
        reason: 'Reported from artwork page',
      })
    } catch {
      // noop
    } finally {
      setReporting(false)
    }
  }

  return (
    <div className="rounded-xl border border-nova-700 bg-panel p-5 shadow-lg shadow-deep/30">
      <h2 className="text-xs font-semibold uppercase tracking-wide text-soft">Actions</h2>
      <div className="mt-4 flex flex-col gap-3">
        {/* Download — full-width primary CTA */}
        <button
          type="button"
          className="inline-flex min-h-11 w-full items-center justify-center gap-2 rounded-lg bg-accent px-4 py-3 text-sm font-semibold text-deep transition hover:brightness-110 disabled:opacity-60 disabled:cursor-wait"
          onClick={handleDownload}
          disabled={downloading}
        >
          {downloading ? (
            <>
              <svg className="h-4 w-4 animate-spin shrink-0" viewBox="0 0 24 24" fill="none">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4l3-3-3-3v4a8 8 0 100 16v-4l-3 3 3 3v-4a8 8 0 01-8-8z" />
              </svg>
              Downloading…
            </>
          ) : (
            <>
              <svg className="h-4 w-4 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M12 4v12m0 0l-4-4m4 4l4-4" />
              </svg>
              Download
            </>
          )}
        </button>

        {/* Secondary actions — icon row */}
        <div className="grid grid-cols-4 gap-2">
          {/* Like */}
          <button
            type="button"
            title={liked ? 'Unlike' : 'Like'}
            onClick={onToggleLike}
            className={`flex flex-col items-center justify-center gap-1 rounded-lg border px-2 py-3 text-xs font-medium transition
              ${liked
                ? 'border-rose-500/60 bg-rose-500/10 text-rose-400 hover:bg-rose-500/20'
                : 'border-nova-600 text-soft hover:bg-nova-800 hover:text-white'}`}
          >
            <svg className="h-5 w-5 shrink-0" fill={liked ? 'currentColor' : 'none'} viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M4.318 6.318a4.5 4.5 0 016.364 0L12 7.636l1.318-1.318a4.5 4.5 0 116.364 6.364L12 20.364l-7.682-7.682a4.5 4.5 0 010-6.364z" />
            </svg>
            <span>{liked ? 'Liked' : 'Like'}</span>
          </button>

          {/* Favorite */}
          <button
            type="button"
            title={favorited ? 'Remove from favorites' : 'Favorite'}
            onClick={onToggleFavorite}
            className={`flex flex-col items-center justify-center gap-1 rounded-lg border px-2 py-3 text-xs font-medium transition
              ${favorited
                ? 'border-amber-500/60 bg-amber-500/10 text-amber-400 hover:bg-amber-500/20'
                : 'border-nova-600 text-soft hover:bg-nova-800 hover:text-white'}`}
          >
            <svg className="h-5 w-5 shrink-0" fill={favorited ? 'currentColor' : 'none'} viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" />
            </svg>
            <span>{favorited ? 'Saved' : 'Save'}</span>
          </button>

          {/* Share */}
          <button
            type="button"
            title="Share"
            onClick={onShare}
            className="flex flex-col items-center justify-center gap-1 rounded-lg border border-nova-600 px-2 py-3 text-xs font-medium text-soft transition hover:bg-nova-800 hover:text-white"
          >
            <svg className="h-5 w-5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z" />
            </svg>
            <span>Share</span>
          </button>

          {/* Report */}
          <button
            type="button"
            title="Report"
            onClick={onReport}
            disabled={reporting}
            className="flex flex-col items-center justify-center gap-1 rounded-lg border border-nova-600 px-2 py-3 text-xs font-medium text-soft transition hover:border-red-500/50 hover:bg-red-500/10 hover:text-red-400 disabled:opacity-50 disabled:cursor-wait"
          >
            <svg className="h-5 w-5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M3 3v1.5M3 21v-6m0 0 2.77-.693a9 9 0 0 1 6.208.682l.108.054a9 9 0 0 0 6.086.71l3.114-.732a48.524 48.524 0 0 1-.005-10.499l-3.11.732a9 9 0 0 1-6.085-.711l-.108-.054a9 9 0 0 0-6.208-.682L3 4.5M3 15V4.5" />
            </svg>
            <span>{reporting ? '…' : 'Report'}</span>
          </button>
        </div>
      </div>

      {mobilePriority && (
        <div className="pointer-events-none fixed inset-x-0 bottom-0 z-50 border-t border-nova-700 bg-panel/95 p-3 backdrop-blur lg:hidden">
          <button
            type="button"
            onClick={handleDownload}
            disabled={downloading}
            className="pointer-events-auto inline-flex min-h-12 w-full items-center justify-center gap-2 rounded-lg bg-accent px-4 py-3 text-sm font-semibold text-deep transition hover:brightness-110 disabled:opacity-60 disabled:cursor-wait"
          >
            {downloading ? 'Downloading…' : 'Download'}
          </button>
        </div>
      )}
    </div>
  )
}
