import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'

import TagLink from '@/components/TagLink'
import FieldError from '@/components/common/FieldError'
import FormField from '@/components/common/FormField'
import PageTitle from '@/components/common/PageTitle'
import MainArea from '@/components/layout/MainArea'
import { toast } from '@/components/ui/use-toast'
import { PLATFORM_NAMES, PLATFORMS } from '@/consts'
import { apiPut } from '@/lib/api'
import { tagsKeys } from '@/lib/queryKeys'
import { fetchDeerjikistsByTag } from '@/lib/tags'
import { cn, inputClass } from '@/lib/utils'
import { useValidationErrors } from '@/lib/useValidationErrors'

import type { FC, FormEvent } from 'react'

import type { Deerjikist, Platform } from '@/types'

type DeerjikistFormField =
    'deerjikists' | `deerjikists${ number }Platform` | `deerjikists${ number }Code`


const DeerjikistDetailPage: FC = () => {
  const { id } = useParams ()
  const tagId = String (id ?? '')
  const tagKey = tagsKeys.deerjikists (tagId)

  const { data: qData, isLoading: loading } =
      useQuery ({ queryKey: tagKey, queryFn: () => fetchDeerjikistsByTag (tagId) })
  const tag = qData?.tag
  const deerjikists = useMemo (() => qData?.deerjikists ?? [], [qData])

  const [data, setData] =
      useState<(Omit<Deerjikist, 'platform'> & { platform: Platform | null })[]> ([])
  const [disabled, setDisabled] = useState (true)
  const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
      useValidationErrors<DeerjikistFormField> ()

  const qc = useQueryClient ()

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault ()
    clearValidationErrors ()

    try
    {
      setDisabled (true)

      setData (await apiPut<Deerjikist[]> (`/tags/${ id }/deerjikists`, data))
      qc.invalidateQueries ({ queryKey: tagsKeys.root })

      toast ({ description: '更新しました．' })
    }
    catch (e)
    {
      applyValidationError (e)
      toast ({ title: '更新失敗', description: '入力内容を確認してください．' })
    }
    finally
    {
      setDisabled (false)
    }
  }

  useEffect (() => {
    if (!(tag))
      {
	setDisabled (true)
	return
      }

    setData (deerjikists)
    setDisabled (false)
  }, [tag, deerjikists])

  return (
      <MainArea>
	{(loading || !(tag)) ? 'Loading...' : (
	    <div className="max-w-xl">
	      <PageTitle>
		<TagLink tag={tag} withWiki={false} withCount={false}/>
	      </PageTitle>

	      <form onSubmit={handleSubmit} className="my-4 space-y-2">
		<FieldError messages={baseErrors}/>
		<FieldError messages={fieldErrors.deerjikists}/>

		{data.map ((datum, i) => (
		    <fieldset key={i} className="min-w-0 rounded-lg border border-gray-300
						 dark:border-gray-700 p-4">
		      <legend className="px-2 text-sm font-semibold text-gray-700
					 dark:text-gray-300">
			<button
			    type="button"
			    disabled={disabled}
			    onClick={() => setData (prev => [...prev.slice (0, i),
							     ...prev.slice (i + 1)])}>
			  #{i + 1}
			</button>
		      </legend>

		      {/* プラットフォーム */}
		      <FormField
			  label="プラットフォーム"
			  messages={fieldErrors[`deerjikists${ i }Platform`]}>
			{({ describedBy, invalid }) => (
			    <select
				disabled={disabled}
				value={datum.platform ?? ''}
				aria-describedby={describedBy}
				aria-invalid={invalid}
				className={inputClass (invalid)}
				onChange={e => setData (prev => {
				  const rtn = [...prev]
				  rtn[i] = { ...rtn[i],
					     platform: (e.target.value || null) as Platform | null }
				  return rtn
				})}>
			      <option value="">&nbsp;</option>
			      {PLATFORMS.map (p => (
				  <option key={p} value={p}>
				    {PLATFORM_NAMES[p]}
				  </option>))}
			    </select>)}
		      </FormField>

		      {/* コード */}
		      <FormField
			  label="コード"
			  messages={fieldErrors[`deerjikists${ i }Code`]}>
			{({ describedBy, invalid }) => (
			    <input
				type="text"
				disabled={disabled}
				value={datum.code}
				aria-describedby={describedBy}
				aria-invalid={invalid}
				className={inputClass (invalid)}
				onChange={e => setData (prev => {
				  const rtn = [...prev]
				  rtn[i] = { ...rtn[i], code: e.target.value }
				  return rtn
				})}/>)}
		      </FormField>
		    </fieldset>
		))}

		<div className="py-3">
		  <button
		      type="button"
		      disabled={disabled}
		      onClick={() => setData (prev => [...prev, { platform: null, code: '' }])}>
		    +
		  </button>
		</div>

		<div className="py-3">
		  <button
		      type="submit"
		      disabled={disabled}
		      className={cn ('px-4 py-2 rounded',
				     (disabled
				      ? 'text-gray-300 bg-gray-500'
				      : 'text-white bg-blue-500'))}>
		    更新
		  </button>
		</div>
	      </form>
	    </div>
	)}
      </MainArea>)
}

export default DeerjikistDetailPage
