'use client'

import React, { useEffect, useState } from 'react'
import { signIn, useSession } from "next-auth/react"
import { ReactNode } from "react"
import { useQuery } from "@tanstack/react-query";

const queryAuthFn = async () => {
  const cookie = await fetch("https://beta.api.cocorobo.cn/api/getcookieuserid", {
    method: "GET",
    credentials: 'include',
  });
  const cookiejson = await cookie.json();
  const user = cookiejson?.[0]?.[0];
  if (cookie.ok && user) {
    return user
  }
  return null
}

const LoadingMask = () => {
  const { status } = useSession()
  if (status === 'loading') {
    return (
      <div className="absolute top-0 left-0 w-full h-full bg-black/50 flex items-center justify-center">
        <span className="loading loading-spinner loading-lg m-auto"></span>
      </div>
    )
  }
  return null
}

const AuthModal = () => {
  const { data: user, refetch } = useQuery({ queryKey: ['auth'], queryFn: queryAuthFn })

  useEffect(() => {
    const intervalId = setInterval(() => {
      refetch()
    }, 5000)
    return () => clearInterval(intervalId)
  }, [refetch])

  useEffect(() => {
    if (user) {
      signIn('credentials', { redirect: false, userId: user.userid })
    }
  }, [user])

  return (
    <dialog className="modal modal-open">
      <div className="modal-box relative">
        <iframe src="https://edu.cocorobo.cn/course/login?type=2"
          style={{ border: "0px", width: "450px", height: "480px" }}></iframe>
        <LoadingMask />
      </div>
    </dialog>
  )
}

export function AuthProvider({ children }: { children: ReactNode }) {
  const { data: session, status } = useSession()


  if (status === 'authenticated') {
    return children
  }
  return (
    <AuthModal />
  )
}