"use client"

import { Suspense, useEffect, useState } from "react"
import { useSearchParams } from "next/navigation"
import { useDriveMountMutations } from "@/lib/api/hooks/use-drive-queries"
import { Button } from "@/components/ui/button"
import { buildDriveMountOAuthRedirectURI } from "@/lib/drive/drive-mount-oauth"

function DriveMountOAuthCallbackInner() {
  const searchParams = useSearchParams()
  const { completeOAuth } = useDriveMountMutations()
  const [message, setMessage] = useState("Finalisation de la connexion…")
  const [done, setDone] = useState(false)

  useEffect(() => {
    const code = searchParams.get("code")
    const mountId = searchParams.get("state") ?? searchParams.get("mount_id")
    if (!code || !mountId) {
      setMessage("Paramètres OAuth manquants.")
      setDone(true)
      return
    }
    void completeOAuth
      .mutateAsync({ mountId, code, redirectUri: buildDriveMountOAuthRedirectURI() })
      .then(() => {
        setMessage("Volume connecté avec succès.")
        setDone(true)
        if (window.opener) {
          window.opener.postMessage({ type: "drive-mount-oauth-complete", mountId }, window.location.origin)
          window.setTimeout(() => window.close(), 800)
        }
      })
      .catch(() => {
        setMessage("Échec de la connexion OAuth. Réessayez depuis UltiDrive.")
        setDone(true)
      })
  }, [completeOAuth, searchParams])

  return (
    <div className="flex min-h-[50vh] flex-col items-center justify-center gap-4 p-6 text-center">
      <p className="text-sm text-muted-foreground">{message}</p>
      {done && !window.opener ? (
        <Button asChild variant="outline">
          <a href="/drive">Retour à UltiDrive</a>
        </Button>
      ) : null}
    </div>
  )
}

export default function DriveMountOAuthCallbackPage() {
  return (
    <Suspense fallback={<div className="p-6 text-sm text-muted-foreground">Chargement…</div>}>
      <DriveMountOAuthCallbackInner />
    </Suspense>
  )
}
