'use client'

import { useState } from 'react'
import { useMessage } from '@/hooks/useMessage'
import { setSession, login } from '@/lib/authActions'
import { sessionStore } from '@/store/commonAtom'
import { useRecoilState } from 'recoil'
import { useAxios } from '@/hooks/useAxios'
import { globalLocaleStore } from '@/store/localeAtom'
import { useRouter } from 'next/navigation'
import Cookies from 'js-cookie'

import GlobalSpinner from '@/components/common/spinner/GlobalSpinner'

export default function AutoLoginPage({ autoLoginParam }) {
  const router = useRouter()

  const [isLoading, setIsLoading] = useState(autoLoginParam === 'Y' ? false : true)
  const [globalLocaleState, setGlbalLocaleState] = useRecoilState(globalLocaleStore)

  const { promisePost } = useAxios(globalLocaleState)
  const { getMessage } = useMessage()

  const [userId, setUserId] = useState('')
  const [sessionState, setSessionState] = useRecoilState(sessionStore)

  const [idFocus, setIdFocus] = useState(false)

  const loginProcess = async () => {
    setIsLoading(true)
    await promisePost({ url: '/api/login/v1.0/user', data: { loginId: userId } }).then((response) => {
      setIsLoading(false)
      if (response.data) {
        const res = response.data
        if (res.sessionId) Cookies.set('sessionId', res.sessionId)
        const result = { ...res, storeLvl: res.groupId === '60000' ? '1' : '2', pwdInitYn: 'Y' }
        setSession(result)
        setSessionState(result)
        login()
      } else {
        alert(getMessage('login.fail'))
        router.push('/login?autoLoginParam1=Y')
      }
    })
  }

  return (
    <>
      {isLoading && <GlobalSpinner />}
      {autoLoginParam !== 'Y' ? (
        <>
          <div className="login-input-frame">
            <div className="login-frame-tit ">
              <span>{getMessage('site.name')}</span>
              {getMessage('site.sub_name')}
            </div>
            <div className="login-input-wrap">
              <div className="login-area id" style={{ fontWeight: 'bolder' }}>
                {getMessage('login.auto.page.text')}
              </div>
            </div>
          </div>
        </>
      ) : (
        <>
          <div className="login-input-frame">
            <form
              onSubmit={(e) => {
                e.preventDefault()
                loginProcess()
              }}
              className="space-y-6"
            >
              <div className="login-frame-tit">
                <span>{getMessage('site.name')}</span>
                {getMessage('site.sub_name')}
              </div>
              <div className="login-input-wrap">
                <div className={`login-area id ${idFocus ? 'focus' : ''}`}>
                  <input
                    type="text"
                    className="login-input"
                    id="userId"
                    name="id"
                    required
                    value={userId}
                    placeholder={getMessage('login.id.placeholder')}
                    onChange={(e) => {
                      setUserId(e.target.value)
                    }}
                    onFocus={() => setIdFocus(true)}
                    onBlur={() => setIdFocus(false)}
                  />
                  <button
                    type="button"
                    className="id-delete"
                    onClick={(e) => {
                      setUserId('')
                    }}
                  ></button>
                </div>
                <div className="login-btn-box">
                  <button type="submit" className="login-btn">
                    {getMessage('login')}
                  </button>
                </div>
              </div>
            </form>
          </div>
        </>
      )}
    </>
  )
}
