import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet-async'

import Form from '@/components/common/Form'
import Label from '@/components/common/Label'
import PageTitle from '@/components/common/PageTitle'
import MainArea from '@/components/layout/MainArea'
import InheritDialogue from '@/components/users/InheritDialogue'
import UserCodeDialogue from '@/components/users/UserCodeDialogue'
import { Button } from '@/components/ui/button'
import { toast } from '@/components/ui/use-toast'
import { SITE_TITLE } from '@/config'
import { apiPut } from '@/lib/api'

import type { User } from '@/types'

type Props = { user:    User | null
	       setUser: React.Dispatch<React.SetStateAction<User | null>> }


export default ({ user, setUser }: Props) => {
  const [name, setName] = useState ('')
  const [userCodeVsbl, setUserCodeVsbl] = useState (false)
  const [inheritVsbl, setInheritVsbl] = useState (false)

  const handleSubmit = async () => {
    if (!(user))
      return

    const formData = new FormData
    formData.append ('name', name)

    try
    {
      const data = await apiPut<User> (
	  `/users/${ user.id }`, formData,
	  { headers: { 'Content-Type': 'multipart/form-data' } })
      setUser (user => ({ ...user, ...data }))
      toast ({ title: '設定を更新しました．' })
    }
    catch
    {
      toast ({ title: 'しっぱい……' })
    }
  }

  useEffect (() => {
    if (!user)
      return

    setName (user.name ?? '')
  }, [user])

  return (
      <MainArea>
	<Helmet>
	  <meta name="robots" content="noindex"/>
	  <title>設定 | {SITE_TITLE}</title>
	</Helmet>

	<Form>
	  <PageTitle>設定</PageTitle>

	  {user ? (
	      <>
		{/* 名前 */}
		<div>
		  <Label>表示名</Label>
		  <input type="text"
			 className="w-full border rounded p-2"
			 value={name}
			 placeholder="名もなきニジラー"
			 onChange={ev => setName (ev.target.value)}/>
		  {(user && !(user.name)) && (
		      <p className="mt-1 text-sm text-red-500">
			名前が未設定のアカウントは 30 日間アクセスしないと削除されます!!!!
		      </p>)}
		</div>

		{/* 送信 */}
		<Button onClick={handleSubmit}
			className="px-4 py-2 bg-blue-600 text-white rounded disabled:bg-gray-400">
		  更新
		</Button>

		{/* 引継ぎ */}
		<div>
		  <Label>引継ぎ</Label>
		  <Button onClick={() => setUserCodeVsbl (true)}
			  className="px-4 py-2 bg-gray-600 text-white rounded disabled:bg-gray-400"
			  disabled={!(user)}>
		    引継ぎコードを表示
		  </Button>
		  <Button onClick={() => setInheritVsbl (true)}
			  className="ml-2 px-4 py-2 bg-red-600 text-white rounded disabled:bg-gray-400"
			  disabled={!(user)}>
		    ほかのブラウザから引継ぐ
		  </Button>
		</div>
	      </>) : 'Loading...'}
	</Form>

	<UserCodeDialogue visible={userCodeVsbl}
			  onVisibleChange={setUserCodeVsbl}
			  user={user}
			  setUser={setUser}/>

	<InheritDialogue visible={inheritVsbl}
			 onVisibleChange={setInheritVsbl}
			 setUser={setUser}/>
      </MainArea>)
}
