import type { FC } from 'react'

import { useState } from 'react'

import { useDialogue } from '@/components/dialogues/DialogueProvider'
import { Button } from '@/components/ui/button'
import { Dialog,
	 DialogContent,
	 DialogDescription,
	 DialogHeader,
	 DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { toast } from '@/components/ui/use-toast'
import { apiPost } from '@/lib/api'

import type { User } from '@/types'

type Props = { visible:         boolean
	       onVisibleChange: (visible: boolean) => void
	       setUser:         (user: User) => void }


const InheritDialogue: FC<Props> = ({ visible, onVisibleChange, setUser }) => {
  const dialogue = useDialogue ()

  const [inputCode, setInputCode] = useState ('')

  const handleTransfer = async () => {
    if (!(await dialogue.confirm ({
	title: '引継ぎを行ってもよろしいですか?',
	description: '現在のアカウントからはログアウトされます．',
	confirmText: '引継ぐ',
	variant: 'danger' })))
      return

    try
    {
      const data = await apiPost<{ valid: boolean; user: User }> (
	  '/users/verify', { code: inputCode })
      if (data.valid)
	{
	  localStorage.setItem ('user_code', inputCode)
	  setUser (data.user)
	  toast ({ title: '引継ぎ成功!' })
	  onVisibleChange (false)
	}
      else
	toast ({ title: '認証失敗', description: 'そのコードは使へません．' })
    }
    catch
    {
      toast ({ title: '通信エラー', description: 'またあとで試してね．' })
    }
  }

  return (
      <Dialog open={visible} onOpenChange={onVisibleChange}>
	<DialogContent className="px-6 pp-6 pt-7">
	  <DialogHeader className="pl-8">
	    <DialogTitle>ほかのブラウザから引継ぐ</DialogTitle>
	    <DialogDescription asChild>
	      <div className="flex gap-2">
		<Input placeholder="引継ぎコードを入力"
		       value={inputCode}
		       onChange={ev => setInputCode (ev.target.value)}/>
		<Button onClick={handleTransfer}>引継ぐ</Button>
	      </div>
	    </DialogDescription>
	  </DialogHeader>
	</DialogContent>
      </Dialog>)
}

export default InheritDialogue
