'use client'

import { useState, useEffect } from 'react'
import Image from 'next/image'
import Link from 'next/link'
import { useRecoilState } from 'recoil'
import { useAxios } from '@/hooks/useAxios'
import { setSession, login, checkSession } from '@/lib/authActions'
import { useMessage } from '@/hooks/useMessage'
import { globalLocaleStore } from '@/store/localeAtom'
import { sessionStore } from '@/store/commonAtom'
import { redirect, useRouter } from 'next/navigation'
import { useSearchParams } from 'next/navigation'

import GlobalSpinner from '@/components/common/spinner/GlobalSpinner'
import Cookies from 'js-cookie'
import AutoLogin from './AutoLogin'

export default function Login() {
  const [isLoading, setIsLoading] = useState(false)

  // 자동 로그인
  const initParams = useSearchParams()
  const autoLoginParam = initParams.get('autoLoginParam1')

  useEffect(() => {
    if (autoLoginParam) {
      autoLoginProcess(autoLoginParam)
    }

    // console.log('🚀 ~ checkSession ~ checkSession():', checkSession())
    // checkSession().then((res) => {
    //   console.log('🚀 ~ checkSession ~ res:', res)
    //   if (res) {
    //     login()
    //   }
    // })
  }, [])

  const autoLoginProcess = async (autoLoginParam) => {
    setIsLoading(true)
    await promisePost({ url: '/api/login/v1.0/user/login/autoLoginDecryptData', data: { loginId: autoLoginParam } })
      .then((res) => {
        if (res) {
          if (res.data) {
            post({ url: '/api/login/v1.0/user', data: { loginId: res.data } }).then((response) => {
              setIsLoading(false)
              if (response) {
                const result = { ...response, storeLvl: response.groupId === '60000' ? '1' : '2', pwdInitYn: 'Y' }
                setSession(result)
                setSessionState(result)
                login()
              } else {
                router.push('/login', undefined, { shallow: true })
              }
            })
          }
        }
      })
      .catch((error) => {
        setIsLoading(false)
        router.push('/login')
      })
  }

  const [userId, setUserId] = useState('')
  const [checkId, setCheckId] = useState('')
  const [checkEmail, setCheckEmail] = useState('')

  useEffect(() => {
    if (Cookies.get('chkLoginId')) {
      setUserId(Cookies.get('chkLoginId'))
    }
  }, [])

  const [chkLoginId, setChkLoginId] = useState(Cookies.get('chkLoginId') ? true : false)
  const [passwordVisible, setPasswordVisible] = useState(false)
  const router = useRouter()

  const { getMessage } = useMessage()
  const [globalLocaleState, setGlbalLocaleState] = useRecoilState(globalLocaleStore)
  const [sessionState, setSessionState] = useRecoilState(sessionStore)

  const [passwordReset, setPasswordReset] = useState(1)

  const { promisePost, promisePatch, post } = useAxios(globalLocaleState)

  // focus state
  const [idFocus, setIdFocus] = useState(false)
  const [secFocus, setSecFocus] = useState(false)

  // login process
  const loginProcess = async (e) => {
    e.preventDefault()
    const formData = new FormData(e.target)

    // 로그인 처리 시작
    const param = {
      loginId: formData.get('id'),
      pwd: formData.get('password'),
    }
    setIsLoading(true)
    await promisePost({ url: '/api/login/v1.0/login', data: param })
      .then((res) => {
        if (res) {
          setIsLoading(false)
          if (res.data.result.resultCode === 'S') {
            setSession(res.data.data)
            setSessionState(res.data.data)
            // ID SAVE 체크되어 있는 경우, 쿠키 저장
            if (chkLoginId) {
              Cookies.set('chkLoginId', formData.get('id'), { expires: 7 })
            } else {
              Cookies.remove('chkLoginId')
            }
            login()
          } else {
            alert(res.data.result.resultMsg)
          }
        }
      })
      .catch((error) => {
        setIsLoading(false)
        alert(error.response.data.message)
      })
  }

  // 비밀번호 초기화 관련
  const initPasswordProcess = async () => {
    const param = {
      loginId: checkId,
      email: checkEmail,
    }
    setIsLoading(true)
    await promisePatch({
      url: '/api/login/v1.0/user/init-password',
      data: param,
    })
      .then((res) => {
        if (res) {
          setIsLoading(false)
          if (res.data.result.resultCode == 'S') {
            alert(getMessage('login.init_password.complete_message'))
            setCheckId('')
            setCheckEmail('')
            setPasswordReset(1)
          } else {
            alert(res.data.result.resultMsg)
          }
        }
      })
      .catch((error) => {
        setIsLoading(false)
        alert(error.response.data.message)
      })
  }

  return (
    <>
      {isLoading && <GlobalSpinner />}
      <div className="login-wrap">
        <div className="login-inner">
          <Link href={'/login'} className="login-logo">
            <Image
              src="/static/images/main/login-logo.svg"
              alt="react"
              width={236}
              height={43}
              styles={{ width: '236px', height: '43px' }}
              priority
            />
          </Link>
          {!autoLoginParam && passwordReset === 1 && (
            <>
              <div className="login-input-frame">
                <form onSubmit={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-area password ${secFocus ? 'focus' : ''}`}>
                      <input
                        type={passwordVisible ? 'text' : 'password'}
                        className="login-input"
                        id="password"
                        name="password"
                        required
                        autoComplete="current-password"
                        placeholder={getMessage('login.password.placeholder')}
                        onChange={(e) => {
                          setPasswordVisible(passwordVisible)
                        }}
                        onFocus={() => setSecFocus(true)}
                        onBlur={() => setSecFocus(false)}
                      />
                      <button
                        type="button"
                        className={`password-hidden ${passwordVisible ? 'visible' : ''}`}
                        onClick={(e) => {
                          e.preventDefault()
                          setPasswordVisible(!passwordVisible)
                        }}
                      ></button>
                    </div>
                    <div className="d-check-box login">
                      <input
                        type="checkbox"
                        id="ch01"
                        name="chkLoginId"
                        checked={chkLoginId}
                        onChange={(e) => {
                          setChkLoginId(e.target.checked)
                        }}
                      />
                      <label htmlFor="ch01">{getMessage('login.id.save')}</label>
                    </div>
                    <div className="login-btn-box">
                      <button type="submit" className="login-btn">
                        {getMessage('login')}
                      </button>
                    </div>
                    <div className="reset-password">
                      <button type="button" onClick={() => setPasswordReset(2)}>
                        {getMessage('login.init_password.btn')}
                      </button>
                    </div>
                  </div>
                </form>
              </div>
              <div className="login-guide-wrap">
                <span>※</span>
                {getMessage('login.guide.text')}
                <br />
                {getMessage('login.guide.sub1')} <Link href={'../join'}>{getMessage('login.guide.join.btn')}</Link>
                {getMessage('login.guide.sub2')}
              </div>
            </>
          )}
          {!autoLoginParam && passwordReset === 2 && (
            <>
              <div className="login-input-frame">
                <div className="login-frame-tit pw-reset">
                  <span>{getMessage('login.init_password.title')}</span>
                  {getMessage('login.init_password.sub_title')}
                </div>
                <div className="login-input-wrap">
                  <div className={`login-area id ${idFocus ? 'focus' : ''}`}>
                    <input
                      type="text"
                      id="checkId"
                      name="checkId"
                      value={checkId}
                      required
                      className="login-input"
                      placeholder={getMessage('login.init_password.id.placeholder')}
                      onChange={(e) => {
                        setCheckId(e.target.value)
                      }}
                      onFocus={() => setIdFocus(true)}
                      onBlur={() => setIdFocus(false)}
                    />
                    <button
                      type="button"
                      className="id-delete"
                      onClick={() => {
                        setCheckId('')
                      }}
                    ></button>
                  </div>
                  <div className={`login-area email ${secFocus ? 'focus' : ''}`}>
                    <input
                      id="checkEmail"
                      name="checkEmail"
                      type="email"
                      required
                      className="login-input"
                      value={checkEmail}
                      onChange={(e) => {
                        setCheckEmail(e.target.value)
                      }}
                      placeholder={getMessage('login.init_password.email.placeholder')}
                      onFocus={() => setSecFocus(true)}
                      onBlur={() => setSecFocus(false)}
                    />
                    <button
                      type="button"
                      className="id-delete"
                      onClick={() => {
                        setCheckEmail('')
                      }}
                    ></button>
                  </div>
                  <div className="pwreset-btn-box">
                    <button
                      type="button"
                      className="login-btn light mr5"
                      onClick={() => {
                        setPasswordReset(1)
                        setCheckEmail('')
                        setCheckId('')
                      }}
                    >
                      {getMessage('login.init_password.btn.back')}
                    </button>
                    <button type="button" className="login-btn" onClick={initPasswordProcess}>
                      {getMessage('login.init_password.btn')}
                    </button>
                  </div>
                </div>
              </div>
            </>
          )}
          {autoLoginParam && <AutoLogin />}
        </div>
        <div className="login-copyright">COPYRIGHT©2024 Hanwha Japan All Rights Reserved.</div>
      </div>
    </>
  )
}
