import { useQuery } from '@tanstack/react-query'
import { useEffect, useMemo, useState } from 'react'
import { Helmet } from 'react-helmet-async'
import { useLocation, useNavigate } from 'react-router-dom'

import nikumaru from '@/assets/fonts/nikumaru.otf'
import PrefetchLink from '@/components/PrefetchLink'
import DateTimeField from '@/components/common/DateTimeField'
import FormField from '@/components/common/FormField'
import PageTitle from '@/components/common/PageTitle'
import Pagination from '@/components/common/Pagination'
import MainArea from '@/components/layout/MainArea'
import { API_BASE_URL, SITE_TITLE } from '@/config'
import { fetchMaterials, parseMaterialFilter } from '@/lib/materials'
import { materialsKeys } from '@/lib/queryKeys'
import { dateString, inputClass } from '@/lib/utils'

import type { FC, FormEvent } from 'react'

import type {
    FetchMaterialsParams,
    Material,
    MaterialIndexDirection,
    MaterialIndexMediaKind,
    MaterialIndexSort,
    MaterialIndexTagState,
    MaterialIndexView } from '@/types'

const MEDIA_KIND_LABELS: Record<Material['mediaKind'], string> = {
    image:      '画像',
    video:      '動画',
    audio:      '音声',
    file_other: 'その他ファイル',
    url_only:   'URL のみ'}

const MEDIA_FILTER_LABELS: Record<MaterialIndexMediaKind, string> = {
    all:        'すべて',
    image:      '画像',
    video:      '動画',
    audio:      '音声',
    file_other: 'その他ファイル',
    url_only:   'URL のみ'}

const SORT_LABELS: Record<MaterialIndexSort, string> = {
    created_at:     '作成日時',
    updated_at:     '更新日時',
    tag_name:       'タグ名',
    media_kind:     '種類',
    file_byte_size: 'ファイルサイズ',
    version_no:     'バージョン',
    id:             'ID'}


const setIf = (qs: URLSearchParams, key: string, value: string | null) => {
  const next = value?.trim ()
  if (next)
    qs.set (key, next)
}


const parseOption = <T extends string> (
    value: string | null,
    allowed: readonly T[],
    fallback: T): T => allowed.includes (value as T) ? value as T : fallback


const fileSizeText = (bytes: number | null): string => {
  if (bytes == null)
    return ''
  if (bytes < 1024)
    return `${ bytes } B`
  if (bytes < 1024 * 1024)
    return `${ (bytes / 1024).toFixed (1) } KB`
  return `${ (bytes / 1024 / 1024).toFixed (1) } MB`
}


const materialTitle = (material: Material): string =>
    material.tag?.name ?? `素材 #${ material.id }`


const MaterialThumb: FC<{ material: Material }> = ({ material }) => (
    <div
	className={`flex aspect-square h-[180px] w-[180px] items-center justify-center
		    overflow-hidden rounded-lg border border-stone-200 bg-white text-center
		    text-stone-900 shadow-sm dark:border-stone-700 dark:bg-stone-900
		    dark:text-stone-100`}>
      {material.thumbnail
       ? <img src={material.thumbnail} alt="" className="h-full w-full object-contain"/>
       : (
	  <span
	      className="px-2 text-2xl leading-tight"
	      style={{ fontFamily: material.thumbnailFallbackKind === 'tag_name'
		  ? 'Nikumaru'
		  : undefined }}>
	    {material.thumbnailFallbackText}
	  </span>)}
    </div>)


const MaterialCard: FC<{ material: Material }> = ({ material }) => (
    <article className="w-[180px] justify-self-center">
      <PrefetchLink to={`/materials/${ material.id }`} className="block">
	<MaterialThumb material={material}/>
	<div className="mt-2 w-[180px]">
	  <p className="truncate text-sm font-medium text-stone-900 dark:text-stone-100">
	    {materialTitle (material)}
	  </p>
	  <p className="truncate text-xs text-stone-600 dark:text-stone-300">
	    {MEDIA_KIND_LABELS[material.mediaKind]} / {dateString (material.createdAt)}
	  </p>
	</div>
      </PrefetchLink>
    </article>)


const MaterialListItem: FC<{ material: Material }> = ({ material }) => (
    <article
	className="rounded-lg border border-stone-200 bg-white p-3 text-stone-900
		   shadow-sm dark:border-stone-700 dark:bg-stone-900 dark:text-stone-100">
      <div className="flex gap-3">
	<MaterialThumb material={material}/>
	<div className="min-w-0 flex-1 space-y-2">
	  <div>
	    <PrefetchLink
		to={`/materials/${ material.id }`}
		className="font-medium text-sky-700 underline underline-offset-2
			   dark:text-sky-300">
	      {materialTitle (material)}
	    </PrefetchLink>
	  </div>
	  <dl className="space-y-1 text-sm text-stone-600 dark:text-stone-300">
	    <div>
	      <dt className="inline">種類: </dt>
	      <dd className="inline">{MEDIA_KIND_LABELS[material.mediaKind]}</dd>
	    </div>
	    {material.fileByteSize != null && (
		<div>
		  <dt className="inline">サイズ: </dt>
		  <dd className="inline">{fileSizeText (material.fileByteSize)}</dd>
		</div>)}
	    {material.url && (
		<div>
		  <dt className="inline">URL: </dt>
		  <dd className="inline break-all">{material.url}</dd>
		</div>)}
	    <div>
	      <dt className="inline">作成: </dt>
	      <dd className="inline">{dateString (material.createdAt)}</dd>
	    </div>
	  </dl>
	</div>
      </div>
    </article>)


const MaterialListPage: FC = () => {
  const location = useLocation ()
  const navigate = useNavigate ()
  const query = useMemo (() => new URLSearchParams (location.search), [location.search])
  const materialFilter = parseMaterialFilter (query.get ('material_filter'), 'present')

  const page = Number (query.get ('page') ?? 1)
  const limit = Number (query.get ('limit') ?? 20)
  const qQuery = query.get ('q') ?? query.get ('tag') ?? ''
  const tagState = query.get ('unclassified') === '1'
      ? 'untagged'
      : parseOption<MaterialIndexTagState> (
	  query.get ('tag_state'),
	  ['all', 'tagged', 'untagged'],
	  'all')
  const mediaKind = parseOption<MaterialIndexMediaKind> (
      query.get ('media_kind'),
      ['all', 'image', 'video', 'audio', 'file_other', 'url_only'],
      'all')
  const sort = parseOption<MaterialIndexSort> (
      query.get ('sort'),
      ['created_at', 'updated_at', 'tag_name', 'media_kind', 'file_byte_size',
       'version_no', 'id'],
      'created_at')
  const direction = parseOption<MaterialIndexDirection> (
      query.get ('direction'),
      ['asc', 'desc'],
      'desc')
  const view = parseOption<MaterialIndexView> (query.get ('view'), ['card', 'list'], 'card')
  const createdFromQuery = query.get ('created_from') ?? ''
  const createdToQuery = query.get ('created_to') ?? ''
  const updatedFromQuery = query.get ('updated_from') ?? ''
  const updatedToQuery = query.get ('updated_to') ?? ''

  const [q, setQ] = useState ('')
  const [tagStateInput, setTagStateInput] = useState<MaterialIndexTagState> ('all')
  const [mediaKindInput, setMediaKindInput] = useState<MaterialIndexMediaKind> ('all')
  const [createdFrom, setCreatedFrom] = useState<string | null> (null)
  const [createdTo, setCreatedTo] = useState<string | null> (null)
  const [updatedFrom, setUpdatedFrom] = useState<string | null> (null)
  const [updatedTo, setUpdatedTo] = useState<string | null> (null)

  const keys: FetchMaterialsParams = {
      q: qQuery,
      tagState,
      mediaKind,
      createdFrom: createdFromQuery,
      createdTo: createdToQuery,
      updatedFrom: updatedFromQuery,
      updatedTo: updatedToQuery,
      sort,
      direction,
      view,
      page,
      limit}
  const { data, isLoading, isError } = useQuery ({
      queryKey: materialsKeys.index (keys),
      queryFn:  () => fetchMaterials (keys)})
  const materials = data?.materials ?? []
  const totalPages = data ? Math.ceil (data.count / limit) : 0

  useEffect (() => {
    setQ (qQuery)
    setTagStateInput (tagState)
    setMediaKindInput (mediaKind)
    setCreatedFrom (createdFromQuery)
    setCreatedTo (createdToQuery)
    setUpdatedFrom (updatedFromQuery)
    setUpdatedTo (updatedToQuery)
  }, [createdFromQuery, createdToQuery, mediaKind, qQuery, tagState,
      updatedFromQuery, updatedToQuery])

  const search = (e: FormEvent) => {
    e.preventDefault ()

    const qs = new URLSearchParams ()
    setIf (qs, 'q', q)
    qs.set ('tag_state', tagStateInput)
    qs.set ('media_kind', mediaKindInput)
    setIf (qs, 'created_from', createdFrom)
    setIf (qs, 'created_to', createdTo)
    setIf (qs, 'updated_from', updatedFrom)
    setIf (qs, 'updated_to', updatedTo)
    qs.set ('sort', sort)
    qs.set ('direction', direction)
    qs.set ('view', view)
    qs.set ('page', '1')
    qs.set ('limit', String (limit))
    qs.set ('material_filter', materialFilter)
    navigate (`/materials?${ qs.toString () }`)
  }

  const updateQuery = (changes: Record<string, string>) => {
    const qs = new URLSearchParams (location.search)
    Object.entries (changes).forEach (([key, value]) => qs.set (key, value))
    navigate (`/materials?${ qs.toString () }`)
  }

  return (
      <MainArea>
	<Helmet>
	  <style>
	    {`
		@font-face
		{
		  font-family: 'Nikumaru';
		  src: url(${ nikumaru }) format('opentype');
		}`}
	  </style>
	  <title>{`素材一覧 | ${ SITE_TITLE }`}</title>
	</Helmet>

	<div className="space-y-5">
	  <div className="flex flex-wrap items-center justify-between gap-3">
	    <PageTitle>素材一覧</PageTitle>
	    <div className="flex flex-wrap gap-2">
	      <PrefetchLink
		  to="/materials/new"
		  className="rounded-full border border-stone-300 bg-white px-4 py-2 text-sm
			     text-stone-900 hover:bg-stone-100 dark:border-stone-700
			     dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
		新規素材を追加
	      </PrefetchLink>
	      <PrefetchLink
		  to="/materials/suppressions"
		  className="rounded-full border border-stone-300 bg-white px-4 py-2 text-sm
			     text-stone-900 hover:bg-stone-100 dark:border-stone-700
			     dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
		同期元抑止
	      </PrefetchLink>
	      <a
		  href={`${ API_BASE_URL }/materials/download.zip?profile=legacy_drive`}
		  target="_blank"
		  rel="noopener noreferrer"
		  className="rounded-full border border-stone-300 bg-white px-4 py-2 text-sm
			     text-stone-900 hover:bg-stone-100 dark:border-stone-700
			     dark:bg-stone-900 dark:text-stone-100 dark:hover:bg-stone-800">
		ZIP をダウンロード
	      </a>
	    </div>
	  </div>

	  {tagState === 'untagged' && (
	      <PrefetchLink
		  to={`/materials?material_filter=${ materialFilter }`}
		  className="text-sm text-sky-700 underline underline-offset-2 dark:text-sky-300">
		素材検索トップへ戻る
	      </PrefetchLink>)}

	  <form
	      onSubmit={search}
	      className="max-w-3xl rounded-lg border border-stone-200 bg-white p-4
			 text-stone-900 dark:border-stone-700 dark:bg-stone-900
			 dark:text-stone-100">
	    <div className="space-y-3">
	      <FormField label="検索">
		{({ invalid }) => (
		    <input
			type="search"
			value={q}
			onChange={e => setQ (e.target.value)}
			placeholder="タグ名 / URL / ファイル名"
			className={inputClass (invalid)}/>)}
	      </FormField>

	      <FormField label="タグ状態">
		{({ invalid }) => (
		    <select
			value={tagStateInput}
			onChange={e => setTagStateInput (
			    e.target.value as MaterialIndexTagState)}
			className={inputClass (invalid)}>
		      <option value="all">すべて</option>
		      <option value="tagged">タグあり</option>
		      <option value="untagged">タグなし</option>
		    </select>)}
	      </FormField>

	      <FormField label="メディア">
		{({ invalid }) => (
		    <select
			value={mediaKindInput}
			onChange={e => setMediaKindInput (
			    e.target.value as MaterialIndexMediaKind)}
			className={inputClass (invalid)}>
		      {Object.entries (MEDIA_FILTER_LABELS).map (([value, label]) => (
			  <option key={value} value={value}>
			    {label}
			  </option>))}
		    </select>)}
	      </FormField>

	      <FormField label="作成日時">
		{() => (
		    <div className="flex flex-wrap items-center gap-2">
		      <DateTimeField value={createdFrom ?? undefined} onChange={setCreatedFrom}/>
		      <span>〜</span>
		      <DateTimeField value={createdTo ?? undefined} onChange={setCreatedTo}/>
		    </div>)}
	      </FormField>

	      <FormField label="更新日時">
		{() => (
		    <div className="flex flex-wrap items-center gap-2">
		      <DateTimeField value={updatedFrom ?? undefined} onChange={setUpdatedFrom}/>
		      <span>〜</span>
		      <DateTimeField value={updatedTo ?? undefined} onChange={setUpdatedTo}/>
		    </div>)}
	      </FormField>
	    </div>

	    <div className="mt-4 flex flex-wrap gap-3">
	      <button
		  type="submit"
		  className="rounded bg-sky-600 px-4 py-2 text-white hover:bg-sky-700
			     dark:bg-sky-500 dark:text-stone-950 dark:hover:bg-sky-400">
		検索
	      </button>
	    </div>
	  </form>

	  <div className="flex flex-wrap items-center justify-between gap-3">
	    <div className="flex flex-wrap gap-2">
	      <button
		  type="button"
		  onClick={() => updateQuery ({ view: 'card' })}
		  className={`rounded-full border px-4 py-2 text-sm ${
		      view === 'card'
		      ? [
			  'border-sky-500 bg-sky-50 text-sky-700 dark:border-sky-400',
			  'dark:bg-sky-950 dark:text-sky-100'].join (' ')
		      : [
			  'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
			  'dark:bg-stone-900 dark:text-stone-100'].join (' ') }`}>
		カード
	      </button>
	      <button
		  type="button"
		  onClick={() => updateQuery ({ view: 'list' })}
		  className={`rounded-full border px-4 py-2 text-sm ${
		      view === 'list'
		      ? [
			  'border-sky-500 bg-sky-50 text-sky-700 dark:border-sky-400',
			  'dark:bg-sky-950 dark:text-sky-100'].join (' ')
		      : [
			  'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
			  'dark:bg-stone-900 dark:text-stone-100'].join (' ') }`}>
		一覧
	      </button>
	    </div>

	    <div className="flex flex-wrap items-center gap-2 text-sm">
	      <select
		  value={sort}
		  onChange={e => updateQuery ({ sort: e.target.value, page: '1' })}
		  className={inputClass (false, 'w-auto')}>
		{Object.entries (SORT_LABELS).map (([value, label]) => (
		    <option key={value} value={value}>
		      {label}
		    </option>))}
	      </select>
	      <select
		  value={direction}
		  onChange={e => updateQuery ({ direction: e.target.value, page: '1' })}
		  className={inputClass (false, 'w-auto')}>
		<option value="desc">降順</option>
		<option value="asc">昇順</option>
	      </select>
	    </div>
	  </div>

	  {isLoading && <p>Loading...</p>}
	  {isError && (
	      <p className="text-red-600 dark:text-red-300">素材一覧の取得に失敗しました．</p>)}
	  {(!isLoading && !isError && materials.length === 0) && (
	      <p>素材はありません．</p>)}
	  {materials.length > 0 && (
	      view === 'card'
	      ? (
		  <div className="grid grid-cols-[repeat(auto-fill,minmax(196px,1fr))]
				  justify-items-center gap-4">
		    {materials.map (material => (
			<MaterialCard key={material.id} material={material}/>))}
		  </div>)
	      : (
		  <div className="space-y-3">
		    {materials.map (material => (
			<MaterialListItem key={material.id} material={material}/>))}
		  </div>))}
	  <Pagination page={page} totalPages={totalPages}/>
	</div>
      </MainArea>)
}

export default MaterialListPage
