import React, { useEffect, useState } from 'react'
import { Dialog, DialogTrigger, DialogContent, DialogTitle, DialogDescription } from './ui/dialog'
import { Switch } from './ui/switch'
import { Button } from './ui/button'
import { Input } from '@/components/ui/input'
import { toast } from '@/components/ui/use-toast'
import axios from 'axios'
import { Link, useNavigate, useLocation } from 'react-router-dom'
import { API_BASE_URL } from '../config'
import { camelizeKeys } from 'humps'

type Tag = { id:        number
             name:      string
             category:  string
             count?:    number }

type User = { id:               number
              name:             string | null
              inheritanceCode:  string
              role:             string }

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


const SettingsDialogue: React.FC = ({ visible, onVisibleChange, user, setUser }: Props) => {
  const [inputCode, setInputCode] = useState ('')

  const handleShowCode = () => {
    if (user?.inheritanceCode)
      toast ({ title: 'あなたの引継ぎコード', description: user.inheritanceCode })
    else
      toast ({ title: '引継ぎコードが見つかりません．' })
  }

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

  return (
      <Dialog open={visible} onOpenChange={onVisibleChange}>
        <DialogContent className="space-y-6">
          <DialogTitle>ユーザ設定</DialogTitle>
          <DialogDescription>
            ユーザの設定や引継ぎコードの確認、変更ができます。
          </DialogDescription>
          <div>
            <p className="mb-1 font-semibold">引継ぎコード</p>
            <Button variant="secondary" onClick={handleShowCode}>
              引継ぎコードを表示
            </Button>
          </div>
          <div>
            <p className="mb-1 font-semibold">ほかのブラウザから引継ぐ</p>
            <div className="flex gap-2">
              <Input placeholder="引継ぎコードを入力"
                     value={inputCode}
                     onChange={e => setInputCode (e.target.value)} />
              <Button onClick={handleTransfer}>引継ぐ</Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>)
}


export default SettingsDialogue
