"use client"

import { useEffect, useState } from "react"
import { useSearchParams, useRouter } from "next/navigation"
import { byToken } from "@/services/users/login"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Loader2 } from "lucide-react"

export default function SocmedAuthPage() {
  const searchParams = useSearchParams()
  const router = useRouter()
  const [status, setStatus] = useState<"loading" | "success" | "error">("loading")
  const [message, setMessage] = useState("")

  useEffect(() => {
    const handleTokenLogin = async () => {
      const token = searchParams.get("data")

      if (!token) {
        setStatus("error")
        setMessage("No authentication token provided")
        return
      }

      try {
        console.log("[SOCMED] Processing token login...")
        const result = await byToken(token)

        if (result.success) {
          setStatus("success")
          setMessage("Login successful! Redirecting...")

          // Determine redirect based on user roles
          const userRoles = result.data.roles || []

          // Check if user has admin role
          const hasAdminRole = userRoles.some((role: any) => role.name === "admin" || role.name === "administrator")

          // Check if user has student role
          const hasStudentRole = userRoles.some((role: any) => role.name === "student")

          // Redirect based on role priority: admin > student > default
          setTimeout(() => {
            if (hasAdminRole) {
              router.push("/admin")
            } else if (hasStudentRole) {
              router.push("/student")
            } else {
              router.push("/main")
            }
          }, 1500)
        } else {
          setStatus("error")
          setMessage(result.message || "Authentication failed")
        }
      } catch (error) {
        console.error("[SOCMED] Token login error:", error)
        setStatus("error")
        setMessage("An error occurred during authentication")
      }
    }

    handleTokenLogin()
  }, [searchParams, router])

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 px-4">
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <CardTitle className="text-2xl font-bold">Social Media Authentication</CardTitle>
        </CardHeader>
        <CardContent className="text-center space-y-4">
          {status === "loading" && (
            <>
              <Loader2 className="h-8 w-8 animate-spin mx-auto" />
              <p className="text-gray-600">Processing your authentication...</p>
            </>
          )}

          {status === "success" && (
            <>
              <div className="h-8 w-8 bg-green-100 rounded-full flex items-center justify-center mx-auto">
                <svg className="h-5 w-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
              </div>
              <p className="text-green-600 font-medium">{message}</p>
            </>
          )}

          {status === "error" && (
            <>
              <div className="h-8 w-8 bg-red-100 rounded-full flex items-center justify-center mx-auto">
                <svg className="h-5 w-5 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </div>
              <p className="text-red-600 font-medium">{message}</p>
              <button
                onClick={() => router.push("/auth")}
                className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
              >
                Back to Login
              </button>
            </>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
