import React, { useState } from 'react'
import MasonryGallery from '../gallery/MasonryGallery'

const SORT_OPTIONS = [
  { value: 'latest', label: 'Latest' },
  { value: 'trending', label: 'Trending' },
  { value: 'rising', label: 'Rising' },
  { value: 'views', label: 'Most Viewed' },
  { value: 'favs', label: 'Most Favourited' },
]

function GalleryToolbar({ sort, onSort }) {
  return (
    <div className="mb-5 flex flex-wrap items-center gap-3">
      <span className="text-xs font-semibold uppercase tracking-wider text-slate-500">Sort</span>
      <div className="flex flex-wrap gap-1 rounded-2xl border border-white/10 bg-white/[0.03] p-1">
        {SORT_OPTIONS.map((opt) => (
          <button
            key={opt.value}
            type="button"
            onClick={() => onSort(opt.value)}
            className={`rounded-xl px-3.5 py-2 text-xs font-medium transition-all ${
              sort === opt.value
                ? 'bg-sky-500/20 text-sky-300 ring-1 ring-sky-400/40'
                : 'text-slate-400 hover:bg-white/5 hover:text-white'
            }`}
          >
            {opt.label}
          </button>
        ))}
      </div>
    </div>
  )
}

export default function ProfileGalleryPanel({ artworks, username }) {
  const [sort, setSort] = useState('latest')
  const [items, setItems] = useState(artworks?.data ?? artworks ?? [])
  const [nextCursor, setNextCursor] = useState(artworks?.next_cursor ?? null)

  const handleSort = async (newSort) => {
    setSort(newSort)
    setItems([])

    try {
      const response = await fetch(`/api/profile/${encodeURIComponent(username)}/artworks?sort=${newSort}`, {
        headers: { Accept: 'application/json' },
      })

      if (!response.ok) {
        return
      }

      const data = await response.json()
      setItems(data.data ?? data)
      setNextCursor(data.next_cursor ?? null)
    } catch (_) {}
  }

  return (
    <>
      <div className="mx-auto w-full max-w-6xl px-4 md:px-6">
        <GalleryToolbar sort={sort} onSort={handleSort} />
      </div>

      <div className="w-full px-4 md:px-6 xl:px-8">
        <MasonryGallery
          key={`profile-${username}-${sort}`}
          artworks={items}
          galleryType="profile"
          cursorEndpoint={`/api/profile/${encodeURIComponent(username)}/artworks?sort=${encodeURIComponent(sort)}`}
          initialNextCursor={nextCursor}
          limit={24}
        />
      </div>
    </>
  )
}
