import React, { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet'
import { Link, useLocation } from 'react-router-dom'
import axios from 'axios'
import { API_BASE_URL, SITE_TITLE } from '@/config'
import TagSidebar from '@/components/TagSidebar'
import MainArea from '@/components/layout/MainArea'

import type { Post, Tag } from '@/types'


export default () => {
  const [posts, setPosts] = useState<Post[]> ([])

  const location = useLocation ()
  const query = new URLSearchParams (location.search)
  const tagsQuery = query.get ('tags') ?? ''
  // const anyFlg = query.get ('match') === 'any'
  const anyFlg = false
  const tags = tagsQuery.split (' ').filter (e => e !== '')

  useEffect(() => {
    const fetchPosts = async () => {
      try
      {
        const res = await axios.get (`${ API_BASE_URL }/posts`, {
            params: { tags:   tags.join (','),
                      match:  (anyFlg ? 'any' : 'all') } })
        setPosts (res.data)
      }
      catch (error)
      {
        console.error ('Failed to fetch posts:', error)
        setPosts ([])
      }
    }
    fetchPosts()
  }, [location.search])

  return (
      <>
        <Helmet>
          <title>
            {tags.length
             ? `${ tags.join (anyFlg ? ' or ' : ' and ') } | ${ SITE_TITLE }`
             : `${ SITE_TITLE }　〜 ぼざクリも、ぼざろ外も、外伝もあるんだよ`}
          </title>
        </Helmet>
        <TagSidebar posts={posts} />
        <MainArea>
          <div className="flex flex-wrap gap-4 p-4">
            {posts.map (post => (
              <Link to={`/posts/${ post.id }`}
                    key={post.id}
                    className="w-40 h-40 overflow-hidden rounded-lg shadow-md hover:shadow-lg">
                <img src={post.thumbnail ?? post.thumbnail_base}
                     className="object-none w-full h-full" />
              </Link>
            ))}
          </div>
        </MainArea>
      </>)
}
