import type { FC } from 'react'

import { useDialogue } from '@/components/dialogues/DialogueProvider'
import { Button } from '@/components/ui/button'
import { Dialog,
	 DialogContent,
	 DialogDescription,
	 DialogFooter,
	 DialogHeader,
	 DialogTitle } from '@/components/ui/dialog'
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
	       user:            User | null
	       setUser:         React.Dispatch<React.SetStateAction<User | null>> }


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

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

    if (!(await dialogue.confirm ({
	title: '引継ぎコードを再発行しますか?',
	description: (
	    <div>
	      <p>再発行するとほかのブラウザからはログアウトされます．</p>
	    </div>),
	confirmText: '再発行',
	variant: 'danger' })))
      return

    const data = await apiPost<{ code: string }> ('/users/code/renew', { },
	{ headers: { 'Content-Type': 'multipart/form-data' } })
    if (data.code)
      {
	localStorage.setItem ('user_code', data.code)
	setUser (user => ({ ...user, inheritanceCode: data.code } as User))
	toast ({ title: '再発行しました．' })
      }
  }

  return (
      <Dialog open={visible} onOpenChange={onVisibleChange}>
	<DialogContent className="px-6 pb-6 pt-7">
	  <DialogHeader className="pl-8">
	    <DialogTitle>引継ぎコード</DialogTitle>

	    <DialogDescription asChild>
	      <div>
		<p>あなたの引継ぎコードはこちらです：</p>
		<div className="m-2">{user?.inheritanceCode}</div>
		<p className="mt-1 text-sm text-destructive">
		  このコードはほかの人には教えないでください!
		</p>
	      </div>
	    </DialogDescription>
	  </DialogHeader>

	  <DialogFooter>
	    <Button onClick={handleChange} variant="destructive">
	      引継ぎコード再発行
	    </Button>
	  </DialogFooter>
	</DialogContent>
      </Dialog>)
}

export default UserCodeDialogue
