'use client'

import { useState } from 'react'
import { useAxios } from '@/hooks/useAxios'
import { setSession } from '@/lib/authActions'
import { redirect } from 'next/navigation'
import { useMessage } from '@/hooks/useMessage'

import { Button, Switch } from '@nextui-org/react'
import { useRecoilState } from 'recoil'
import { globalLocaleStore } from '@/store/localeAtom'
import { modalContent, modalState } from '@/store/modalAtom'
import { sessionStore } from '@/store/commonAtom'

export default function Login() {
  const { patch } = useAxios()

  const { getMessage } = useMessage()
  const [globalLocaleState, setGlbalLocaleState] = useRecoilState(globalLocaleStore)
  const [sessionState, setSessionState] = useRecoilState(sessionStore)
  const [isSelected, setIsSelected] = useState(globalLocaleState === 'ko' ? true : false)

  const handleSelected = () => {
    if (isSelected) {
      setGlbalLocaleState('ja')
    } else {
      setGlbalLocaleState('ko')
    }

    setIsSelected(!isSelected)
  }

  // login process
  const loginProcess = async (formData) => {
    const param = {
      // langCd: currentLocale
      langCd: globalLocaleState,
      lastEditUser: formData.get('id'),
      loginId: formData.get('id'),
      pwd: formData.get('password'),
    }

    // await post({ url: '/api/login/v1.0/login', data: param }).then((res) => {
    //   if (res) {
    //     if (res.result.resultCode == 'S') {
    //       // console.log('res.data', res.data)
    //       // 비밀번호 초기화가 필요한 경우
    //       // if (res.data.pwdInitYn != 'Y') {
    //       //   alert('비밀번호 초기화가 필요한 경우')
    //       // } else {
    //       setSession(res.data)
    //       redirect('/')
    //       // }
    //     } else {
    //       alert(res.result.resultMsg)
    //     }
    //   }
    // })

    // 임시 로그인 처리
    setSession({
      userId: 'NEW016610',
      saleStoreId: null,
      name: null,
      mail: null,
      tel: null,
      storeId: 'TEMP02',
      userNm: 'ㅇㅇ6610',
      userNmKana: '신규사용자 16610',
      category: '인상6610',
      telNo: '336610',
      fax: null,
      email: 't10t@naver.com',
      pwdInitYn: 'N',
    })

    setSessionState({
      userId: 'NEW016610',
      saleStoreId: null,
      name: null,
      mail: null,
      tel: null,
      storeId: 'TEMP02',
      userNm: 'ㅇㅇ6610',
      userNmKana: '신규사용자 16610',
      category: '인상6610',
      telNo: '336610',
      fax: null,
      email: 't10t@naver.com',
      pwdInitYn: 'N',
    })

    redirect('/')
    // 임시 로그인 처리 끝
  }

  // 비밀번호 초기화 관련
  const [open, setOpen] = useRecoilState(modalState)
  const [contents, setContent] = useRecoilState(modalContent)

  const initPasswordProcess = async (formData) => {
    const param = {
      langCd: currentLocale,
      lastEditUser: formData.get('checkId'),
      loginId: formData.get('checkId'),
      email: formData.get('checkEmail'),
    }

    await patch({ url: '/api/login/v1.0/user/init-password', data: param }).then((res) => {
      if (res) {
        if (res.result.resultCode == 'S') {
          alert(getMessage('login.init_password.complete_message'))
          redirect('/login')
        } else {
          alert(res.result.resultMsg)
        }
      }
    })
  }

  const initPasswordContent = (
    <div className="flex min-h-full flex-1 flex-col justify-center px-6 py-12 lg:px-8">
      <form action={initPasswordProcess} className="space-y-6">
        <h2 className="text-center text-2xl font-bold leading-9 tracking-tight text-gray-900">{getMessage('login.init_password.title')}</h2>
        <h2 className="text-center text-1xl font-bold leading-9 tracking-tight text-gray-900">{getMessage('login.init_password.sub_title')}</h2>
        <div>
          <label htmlFor="checkId" className="block text-sm font-medium leading-6 text-gray-900">
            ID
          </label>
          <div className="mt-2">
            <input
              id="checkId"
              name="checkId"
              type="text"
              required
              className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
            />
          </div>
        </div>

        <div>
          <div className="flex items-center justify-between">
            <label htmlFor="checkEmail" className="block text-sm font-medium leading-6 text-gray-900">
              E-Mail
            </label>
          </div>
          <div className="mt-2">
            <input
              id="checkEmail"
              name="checkEmail"
              type="email"
              required
              className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
            />
          </div>
        </div>
        <p className="mt-5 text-center text-sm text-gray-500">
          <Button type="submit" className="font-semibold leading-6 text-indigo-600 hover:text-indigo-500">
            {getMessage('login.init_password.btn')}
          </Button>
        </p>
      </form>
    </div>
  )

  return (
    <div className="flex flex-col align-center">
      <div className="flex min-h-full flex-1 flex-col justify-center px-6 py-12 lg:px-8">
        <div className="mt-10 sm:mx-auto sm:w-full sm:max-w-sm">
          <h1 className="text-center text-4xl font-bold leading-9 tracking-tight text-gray-900">{getMessage('site.name')}</h1>
          <h2 className="mt-5 text-center text-2xl font-bold leading-9 tracking-tight text-gray-900">{getMessage('site.sub_name')}</h2>
        </div>

        <div className="mt-5 sm:mx-auto sm:w-full sm:max-w-sm">
          <form action={loginProcess} className="space-y-6">
            <div>
              <label htmlFor="userId" className="block text-sm font-medium leading-6 text-gray-900">
                ID
              </label>
              <div className="mt-2">
                <input
                  id="userId"
                  name="id"
                  type="text"
                  required
                  // autoComplete="email"
                  className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
                />
              </div>
            </div>

            <div>
              <div className="flex items-center justify-between">
                <label htmlFor="password" className="block text-sm font-medium leading-6 text-gray-900">
                  Password
                </label>
              </div>
              <div className="mt-2">
                <input
                  id="password"
                  name="password"
                  type="password"
                  required
                  autoComplete="current-password"
                  className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
                />
              </div>
            </div>

            <div>
              <button
                type="submit"
                className="mt-10 flex w-full justify-center rounded-md bg-indigo-600 px-3 py-1.5 text-sm font-semibold leading-6 text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
              >
                {getMessage('login')}
              </button>
            </div>
          </form>

          <p className="mt-5 text-center text-sm text-gray-500">
            <Button
              onClick={() => {
                setContent(initPasswordContent)
                setOpen(true)
              }}
              className="font-semibold leading-6 text-indigo-600 hover:text-indigo-500"
            >
              {getMessage('login.init_password.btn')}
            </Button>
          </p>

          <div className="flex align-center mt-2">
            <Switch isSelected={isSelected} onValueChange={handleSelected}>
              {isSelected ? 'Current Locale: KO' : 'Current Locale: JA'}
            </Switch>
          </div>
        </div>
      </div>
    </div>
  )
}
