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 { SITE_TITLE } from '@/config'
import { fetchMaterials, parseMaterialFilter } from '@/lib/materials'
import { materialsKeys } from '@/lib/queryKeys'
import { cn, dateString, inputClass } from '@/lib/utils'

import type { FC, FormEvent } from 'react'

import type { FetchMaterialsParams,
	      Material,
	      MaterialFilter,
	      MaterialIndexGroup,
	      MaterialIndexGroupBy,
	      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:   '外部リンクのみ'}

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 groupedTagPath = (
    tagId: number,
    materialFilter: MaterialFilter,
): string =>
    `/materials?tag_id=${ tagId }&include_descendants=1&group_by=parent_tag`
    + `&material_filter=${ materialFilter }`


const materialNewPath = (
    tagName: string,
    returnTo: string,
): string =>
    `/materials/new?tag=${ encodeURIComponent (tagName) }`
    + `&return_to=${ encodeURIComponent (returnTo) }`


const clearedTagSelectionPath = (
    locationSearch: string,
    materialFilter: MaterialFilter,
): string => {
    const qs = new URLSearchParams (locationSearch)
    qs.delete ('tag_id')
    qs.delete ('include_descendants')
    qs.delete ('group_by')
    qs.delete ('page')
    qs.set ('material_filter', materialFilter)
    return `/materials?${ qs.toString () }`
}


const MaterialThumb: FC<{ material: Material }> = ({ material }) => (
    <div
	className={cn (
	    '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="block h-full w-full object-cover"/>
       : (
	  <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 GroupHeading: FC<{
    count:          number
    materialFilter: MaterialFilter
    title:          string
    tagId:          number
}> = ({ count, materialFilter, title, tagId }) => (
    <div className="flex items-center gap-2 border-b border-stone-200 pb-2
		    dark:border-stone-700">
      <PrefetchLink
	  to={groupedTagPath (tagId, materialFilter)}
	  className="font-medium text-sky-700 underline underline-offset-2
		     dark:text-sky-300 w-full">
	{title}
      </PrefetchLink>
      <div className="text-right w-auto">
	<span className="text-nowrap text-sm text-stone-600 dark:text-stone-300">
	  {count} 件
	</span>
      </div>
    </div>)


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') ?? ''
  const tagIdQuery = Number (query.get ('tag_id') ?? 0)
  const tagId = tagIdQuery > 0 ? tagIdQuery : null
  const includeDescendants = query.get ('include_descendants') === '1'
  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 groupByQuery = parseOption<MaterialIndexGroupBy> (
      query.get ('group_by'),
      ['none', 'parent_tag'],
      'none')
  const groupBy = tagId == null ? 'none' : groupByQuery
  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 [groupByInput, setGroupByInput] = useState<MaterialIndexGroupBy> ('none')
  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,
      tagId,
      includeDescendants,
      groupBy,
      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 tagScope = data?.tagScope ?? null
  const materials = data?.materials ?? []
  const groups = data?.groups ?? []
  const totalPages = data ? Math.ceil (data.count / limit) : 0
  const materialsById = useMemo (
      () => new Map (materials.map (material => [material.id, material])),
      [materials],
  )
  const groupedMaterialIds = useMemo (
      () => new Set (groups.flatMap (group => group.materialIds)),
      [groups],
  )
  const ungroupedMaterials = useMemo (
      () => materials.filter (material => !groupedMaterialIds.has (material.id)),
      [groupedMaterialIds, materials],
  )

  useEffect (() => {
    setQ (qQuery)
    setTagStateInput (tagState)
    setMediaKindInput (mediaKind)
    setGroupByInput (groupBy)
    setCreatedFrom (createdFromQuery)
    setCreatedTo (createdToQuery)
    setUpdatedFrom (updatedFromQuery)
    setUpdatedTo (updatedToQuery)
  }, [createdFromQuery, createdToQuery, groupBy, 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 ('group_by', tagId == null ? 'none' : groupByInput)
    qs.set ('view', view)
    qs.set ('page', '1')
    qs.set ('limit', String (limit))
    qs.set ('material_filter', materialFilter)
    if (tagId != null)
      qs.set ('tag_id', String (tagId))

    if (includeDescendants)
      qs.set ('include_descendants', '1')

    navigate (`/materials?${ qs.toString () }`)
  }

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

  const renderMaterialCollection = (rows: Material[]) =>
      view === 'card'
      ? (
	  <div className="grid grid-cols-[repeat(auto-fill,minmax(196px,1fr))]
			  justify-items-center gap-4">
	    {rows.map (material => (
		<MaterialCard key={material.id} material={material}/>))}
	  </div>)
      : (
	  <div className="space-y-3">
	    {rows.map (material => (
		<MaterialListItem key={material.id} material={material}/>))}
	  </div>)

  const renderGroupedMaterials = (materialGroups: MaterialIndexGroup[]) => (
      <div className="space-y-6">
	{materialGroups.map (group => {
	  const groupMaterials =
	      group.materialIds
	      .map (materialId => materialsById.get (materialId))
	      .filter ((material): material is Material => material != null)

	  if (groupMaterials.length === 0)
	    return null

	  return (
	      <section key={group.key} className="space-y-3">
		<GroupHeading
		    tagId={group.tag.id}
		    title={group.tag.name}
		    count={group.count}
		    materialFilter={materialFilter}/>
		{renderMaterialCollection (groupMaterials)}
	      </section>)
	})}
	{ungroupedMaterials.length > 0 && (
	    <section className="space-y-3">
	      <div className="border-b border-stone-200 pb-2 dark:border-stone-700">
		<span className="font-medium text-stone-900 dark:text-stone-100">
		  その他
		</span>
	      </div>
	      {renderMaterialCollection (ungroupedMaterials)}
	    </section>)}
      </div>)

  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 className="my-auto">素材管理</PageTitle>
	    <div className="flex flex-wrap gap-2">
	      {/* TODO: 局所出力を可能にする */}
	      {/* <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>

	  {tagScope && (
	      <div className="flex flex-wrap items-center gap-3 rounded-lg border
			      border-sky-200 bg-sky-50 px-4 py-3 text-sm text-sky-900
			      dark:border-sky-800 dark:bg-sky-950 dark:text-sky-100">
		<span>
		  {tagScope.tag.name}
		  {tagScope.includeDescendants ? ' 配下の素材を表示中' : ' の素材を表示中'}
		</span>
		<PrefetchLink
		    to={clearedTagSelectionPath (location.search, materialFilter)}
		    className="font-medium underline underline-offset-2
			       text-sky-700 dark:text-sky-300">
		  タグ選択を解除
		</PrefetchLink>
	      </div>)}
	  {(tagId != null && tagScope == null) && (
	      <div className="flex flex-wrap items-center gap-3 rounded-lg border
			      border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900
			      dark:border-amber-800 dark:bg-amber-950 dark:text-amber-100">
		<span>選択中タグが見つかりません．</span>
		<PrefetchLink
		    to={clearedTagSelectionPath (location.search, materialFilter)}
		    className="font-medium underline underline-offset-2
			       text-amber-800 dark:text-amber-200">
		  タグ選択を解除
		</PrefetchLink>
	      </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={cn (
			      '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']
			      : [
				  'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
				  'dark:bg-stone-900 dark:text-stone-100'])}>
		アイコン
	      </button>
		      <button
			  type="button"
			  onClick={() => updateQuery ({ view: 'list' })}
			  className={cn (
			      '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']
			      : [
				  'border-stone-300 bg-white text-stone-900 dark:border-stone-700',
				  'dark:bg-stone-900 dark:text-stone-100'])}>
		詳細
	      </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>
		素材はありません。
		{(tagScope && ['character', 'material'].includes (tagScope.tag.category)) && (
		    <>
		      <PrefetchLink
			  to={materialNewPath (tagScope.tag.name, location.pathname + location.search)}
			  className="font-medium underline underline-offset-2
				     text-sky-700 dark:text-sky-300">
			追加してください
		      </PrefetchLink>。
		    </>)}
	      </p>)}
	  {materials.length > 0 && (
	      groupBy === 'parent_tag' && groups.length > 0
	      ? renderGroupedMaterials (groups)
	      : renderMaterialCollection (materials))}
	  <Pagination page={page} totalPages={totalPages}/>
	</div>
      </MainArea>)
}

export default MaterialListPage
