import axios from 'axios'
import toCamel from 'camelcase-keys'
import { useState } from 'react'

import { Button } from '@/components/ui/button'
import { Dialog,
         DialogContent,
         DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { toast } from '@/components/ui/use-toast'
import { API_BASE_URL } from '@/config'

import type { User } from '@/types'

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


export default ({ visible, onVisibleChange, setUser }: Props) => {
  const [inputCode, setInputCode] = useState ('')

  const handleTransfer = async () => {
    if (!(confirm ('引継ぎを行ってもよろしいですか?\n現在のアカウントからはログアウトされます．')))
      return

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

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