'use client'
import { BsCaretDownFill } from "react-icons/bs";
import { useSession, signIn, signOut } from "next-auth/react"
import { createRef, useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { trpc } from "@/lib/trpc";
import Cookies from 'js-cookie';

export default function Header() {
  const { data: session, status } = useSession()

  const [org, setOrg] = useState('')
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [isLogInFail, setIsLogInFail] = useState(false)

  const orgQuery = trpc.org.bySlug.useQuery({ mode: org })

  const logOut = async () => {
    const res = await fetch(" beta.api.cocorobo.cn/api/logout", {
      method: "GET",
      headers: {
        Origin: "https://edu.cocorobo.cn"
      },
    });
    await signOut({ redirect: false })
  }
  const logIn = async () => {
    const loginUsername = orgQuery.data?.mail ? `${username}@${orgQuery.data?.mail}` : `${username}@cocorobo.cc`
    const loginPassword = btoa(password)
    const res = await signIn('credentials', { redirect: false, loginUsername, loginPassword })
    console.log(res)
    if (!res.ok) {
      setIsLogInFail(true)
    }
  }

  // useEffect(() => {
  //   setIsLogInFail(false)
  // }, [username, password, org])


  /*
  用户登陆判断
*/
  useEffect(() => {
    const checkLoginStatus = async (intervalId) => {
      // 检查名为 'authToken' 的 cookie 是否存在
      const authToken = Cookies.get('cocorobo');
      console.log(authToken)
      const tf = authToken ? true : false;
      if (status !== 'authenticated') {//tf &&
        const cookie = await fetch("https://beta.api.cocorobo.cn/api/getcookieuserid", {
          method: "GET",
          credentials: 'include',
        });
        try {
          const cookiejson = await cookie.json();
          console.log(cookiejson);
          const user = cookiejson?.[0]?.[0];
          if (cookie.ok && user) {
            const res = await signIn('credentials', { redirect: false, userid: user.userid })
            setIsLogInFail(true);
            clearInterval(intervalId);
          }
        }
        catch (e) {
          setIsLogInFail(false)
        }
      }
      setIsLogInFail(authToken); // 如果存在 authToken，则用户已登录
    };
    console.log("start")
    const intervalId = setInterval(async () => {
      await checkLoginStatus(intervalId);
    }, 5000);
    return () => {
      clearInterval(intervalId)
    }
  }, []);

  return (
    <div className="navbar shrink-0 bg-base-100 shadow-xl rounded-box justify-center min-h-4 relative">
      <div className="dropdown">
        <div tabIndex={0} role="button" className="btn btn-sm btn-wide btn-ghost">选择对话<BsCaretDownFill /></div>
        <ul tabIndex={0} className="dropdown-content menu bg-base-100 rounded-box z-[1] w-52 p-2 shadow">
          <li><a>Item 1</a></li>
          <li><a>Item 2</a></li>
        </ul>
      </div>
      {status === 'authenticated'
        ? (
          <div className="absolute right-4 flex gap-2">
            <div>
              <p>Hi, {session.user?.name}</p>
            </div>
            <button className='btn btn-sm' onClick={logOut}>退出登录</button>
          </div>
        ) : (
          <>
            <dialog className="modal modal-close" onCancel={event => event.preventDefault()}>
              <div className="modal-box">
                <iframe src="https://edu.cocorobo.cn/course/login?type=2"
                  style={{ border: "0px", width: "450px", height: "480px" }}></iframe>
              </div>
              <div className="modal-box" style={{ display: "none" }} >
                <h3 className="font-bold text-lg" >您需要先登录</h3>
                <div className="w-full flex flex-col items-center gap-2 py-2">
                  {isLogInFail && <div role="alert" className="alert alert-error">
                    <span>账号或密码错误</span>
                  </div>}
                  <label className="form-control w-full max-w-xs">
                    <div className="label">
                      <span className="label-text">组织(选填)</span>
                      {orgQuery?.data?.name && <span className="label-text-alt text-indigo-400">{orgQuery.data.name}</span>}
                    </div>
                    <input type="text" placeholder="" className="input input-bordered w-full max-w-xs" onChange={e => setOrg(e.target.value)} />
                  </label>
                  <label className="form-control w-full max-w-xs">
                    <div className="label">
                      <span className="label-text">用户名</span>
                    </div>
                    <input type="text" placeholder="" className="input input-bordered w-full max-w-xs" onChange={e => setUsername(e.target.value)} />
                  </label>
                  <label className="form-control w-full max-w-xs">
                    <div className="label">
                      <span className="label-text">密码</span>
                    </div>
                    <input type="password" placeholder="" className="input input-bordered w-full max-w-xs" onChange={e => setPassword(e.target.value)} />
                  </label>
                  <button className='btn btn-wide' disabled={!username || !password} onClick={logIn}>登录</button>
                </div>
              </div>
            </dialog>
          </>
        )
      }
    </div >
  )
}