'use client'

import { useEffect, useState } from 'react'
import axios from 'axios'
import { BackButton } from '@/app/components/BackButton'
import { ReloadButton } from '@/app/components/ReloadButton'
import { UploadButton } from '@/app/components/UploadButton'

interface MarketplaceIcon {
  username: string
  userId: number
  data: string
  hash: string
  id: string
  price: number
  buyable: boolean
  name: string
}

export default function BerryDashIconMarketplace () {
  const [response, setResponse] = useState<MarketplaceIcon[] | null | -1>(null)

  async function Refresh () {
    try {
      const request = await axios.get('/api/berrydash/icon-marketplace')
      setResponse(request.data.success ? request.data.data : -1)
    } catch {
      setResponse(-1)
    }
  }

  useEffect(() => {
    document.title = 'Lncvrt Games - Berry Dash Icon Marketplace'
    Refresh()
  }, [])

  return (
    <div className='box text-center'>
      <BackButton href='/game/berry-dash' />
      <UploadButton href='/game/berry-dash/icon-marketplace/upload' />
      <ReloadButton
        action={() => {
          setResponse(null)
          Refresh()
        }}
      />
      <p className='px-20 -mt-2 mb-4 text-2xl'>Berry Dash Icon Marketplace</p>
      <p>A browser for the in game icon marketplace!</p>
      <div className='sub-box mt-2 -mx-4 -mb-4 flex flex-row flex-wrap justify-center gap-2 max-w-[95vw]'>
        {response == null || response == -1 ? (
          <p className='text-2xl'>
            {response != -1 ? 'Loading...' : 'Failed to get marketplace icons'}
          </p>
        ) : (
          response.map(icon => (
            <div className='sub-box2'>
              <div className='bg-(--col8) rounded-md w-fit h-fit p-2 mx-auto'>
                <img
                  src={`data:image/png;base64,${icon.data}`}
                  width={96}
                  height={96}
                  draggable={false}
                  className='pointer-events-none'
                />
              </div>
              <p>Bird Name: {icon.name}</p>
              <p>Price: {icon.price}</p>
              <p>Designer Name: {icon.username}</p>
            </div>
          ))
        )}
      </div>
    </div>
  )
}
