import { useQuery } from '@tanstack/react-query'
import { motion } from 'framer-motion'
import { useEffect } from 'react'
import { Helmet } from 'react-helmet-async'
import { useLocation } from 'react-router-dom'

import TagLink from '@/components/TagLink'
import PrefetchLink from '@/components/PrefetchLink'
import PageTitle from '@/components/common/PageTitle'
import Pagination from '@/components/common/Pagination'
import MainArea from '@/components/layout/MainArea'
import { SITE_TITLE } from '@/config'
import { fetchPostChanges } from '@/lib/posts'
import { postsKeys } from '@/lib/queryKeys'
import { cn, dateString } from '@/lib/utils'

import type { FC } from 'react'


export default (() => {
  const location = useLocation ()
  const query = new URLSearchParams (location.search)
  const id = query.get ('id')
  const page = Number (query.get ('page') ?? 1)
  const limit = Number (query.get ('limit') ?? 20)

  // 投稿列の結合で使用
  let rowsCnt: number

  const { data, isLoading: loading } = useQuery ({
      queryKey: postsKeys.changes ({ ...(id && { id }), page, limit }),
      queryFn:  () => fetchPostChanges ({ ...(id && { id }), page, limit }) })
  const changes = data?.changes ?? []
  const totalPages = data ? Math.ceil (data.count / limit) : 0

  useEffect (() => {
    document.querySelector ('table')?.scrollIntoView ({ behavior: 'smooth' })
  }, [location.search])

  return (
      <MainArea>
	<Helmet>
	  <title>{`耕作履歴 | ${ SITE_TITLE }`}</title>
	</Helmet>

	<PageTitle>
	  耕作履歴
	  {id && <>: 投稿 {<PrefetchLink to={`/posts/${ id }`}>#{id}</PrefetchLink>}</>}
	</PageTitle>

	{loading ? 'Loading...' : (
	    <>
	      <table className="table-auto w-full border-collapse">
		<thead className="border-b-2 border-black dark:border-white">
		  <tr>
		    <th className="p-2 text-left">投稿</th>
		    <th className="p-2 text-left">変更</th>
		    <th className="p-2 text-left">日時</th>
		  </tr>
		</thead>
		<tbody>
		  {changes.map ((change, i) => {
		    let withPost = i === 0 || change.post.id !== changes[i - 1].post.id
		    if (withPost)
		      {
			rowsCnt = 1
			for (let j = i + 1;
			     (j < changes.length
			      && change.post.id === changes[j].post.id);
			     ++j)
			  ++rowsCnt
		      }
		    return (
			<tr key={`${ change.timestamp }-${ change.post.id }-${ change.tag.id }`}
			    className={cn ('even:bg-gray-100 dark:even:bg-gray-700',
					   withPost && 'border-t')}>
			  {withPost && (
			      <td className="align-top p-2 bg-white dark:bg-[#242424] border-r"
				  rowSpan={rowsCnt}>
				<PrefetchLink to={`/posts/${ change.post.id }`}>
				  <motion.div
				      layoutId={`page-${ change.post.id }`}
				      transition={{ type: 'spring',
						    stiffness: 500,
						    damping: 40,
						    mass: .5 }}>
				    <img src={change.post.thumbnail || change.post.thumbnailBase || undefined}
					 alt={change.post.title || change.post.url}
					 title={change.post.title || change.post.url || undefined}
					 className="w-40"/>
				  </motion.div>
				</PrefetchLink>
			      </td>)}
			  <td className="p-2">
			    <TagLink tag={change.tag} withWiki={false} withCount={false}/>
			    {`を${ change.changeType === 'add' ? '記載' : '消除' }`}
			  </td>
			  <td className="p-2">
			    {change.user
			     ? (
				<PrefetchLink to={`/users/${ change.user.id }`}>
				  {change.user.name}
				</PrefetchLink>)
			     : 'bot 操作'}
			    <br/>
			    {dateString (change.timestamp)}
			  </td>
			</tr>)
		  })}
		</tbody>
	      </table>

	      <Pagination page={page} totalPages={totalPages}/>
	    </>)}
      </MainArea>)
}) satisfies FC
