'use client'

import { useEffect, useState } from 'react'
import { useSearchParams, useRouter } from 'next/navigation'
import useAuthStore from '../store/authStore'
import RegisterForm from './components/RegisterForm'
import PageLayout from '../components/PageLayout'
import SessionDetectedModal from './components/SessionDetectedModal'

export default function RegisterPage() {
  const searchParams = useSearchParams()
  const refToken = searchParams.get('ref')
  const [registered, setRegistered] = useState(false)
  const [mode, setMode] = useState<'personal' | 'company'>('personal')
  const router = useRouter()

  // Auth state
  const user = useAuthStore(state => state.user)
  const logout = useAuthStore(state => state.logout)

  // Session management
  const [showSessionModal, setShowSessionModal] = useState(false)
  const [sessionCleared, setSessionCleared] = useState(false)

  // Redirect to login after simulated registration
  useEffect(() => {
    if (registered) {
      const t = setTimeout(() => router.push('/login'), 1200)
      return () => clearTimeout(t)
    }
  }, [registered, router])

  // Detect existing logged-in session
  useEffect(() => {
    if (user && !sessionCleared) setShowSessionModal(true)
  }, [user, sessionCleared])

  const handleLogout = async () => {
    await logout()
    setSessionCleared(true)
    setShowSessionModal(false)
  }

  const handleCancel = () => {
    setShowSessionModal(false)
    router.push('/dashboard')
  }

  return (
    <PageLayout>
      <main className="w-full flex flex-col flex-1 gap-10">
        {/* Background section wrapper */}
        <div className="relative pt-16 sm:pt-20 pb-20 sm:pb-24">
          {/* Pattern */}
          <svg
            aria-hidden="true"
            className="absolute inset-0 -z-10 h-full w-full stroke-white/10"
          >
            <defs>
              <pattern
                id="register-pattern"
                x="50%"
                y={-1}
                width={200}
                height={200}
                patternUnits="userSpaceOnUse"
              >
                <path
                  d="M.5 200V.5H200"
                  fill="none"
                  stroke="rgba(255,255,255,0.05)"
                />
              </pattern>
            </defs>
            <rect
              fill="url(#register-pattern)"
              width="100%"
              height="100%"
              strokeWidth={0}
            />
          </svg>

          {/* Colored blur */}
          <div
            aria-hidden="true"
            className="absolute top-0 right-0 left-1/2 -z-10 -ml-24 transform-gpu overflow-hidden blur-3xl lg:ml-24 xl:ml-48"
          >
            <div
              className="aspect-[801/1036] w-[50.0625rem] bg-gradient-to-tr from-[#ff80b5] to-[#9089fc] opacity-50"
              style={{
                clipPath:
                  'polygon(63.1% 29.5%, 100% 17.1%, 76.6% 3%, 48.4% 0%, 44.6% 4.7%, 54.5% 25.3%, 59.8% 49%, 55.2% 57.8%, 44.4% 57.2%, 27.8% 47.9%, 35.1% 81.5%, 0% 97.7%, 39.2% 100%, 35.2% 81.4%, 97.2% 52.8%, 63.1% 29.5%)'
              }}
            />
          </div>

          {/* Additional background layers */}
          <div className="absolute inset-0 -z-20 bg-gradient-to-b from-gray-900/95 via-gray-900/80 to-gray-900" />
          <div className="pointer-events-none absolute inset-0 -z-10 bg-[radial-gradient(circle_at_30%_20%,rgba(255,255,255,0.1),transparent_65%)]" />

          <div className="mx-auto max-w-7xl px-6 lg:px-8 relative z-10">
            {/* Heading (optional – adjusted to registration context) */}
            <div className="mx-auto max-w-2xl text-center mb-10">
              <h1 className="text-4xl font-semibold tracking-tight text-white sm:text-5xl">
                Registriere dich jetzt
              </h1>
              <p className="mt-2 text-lg/8 text-gray-300">
                Erstelle dein persönliches oder Unternehmens-Konto bei Profit
                Planet.
              </p>
            </div>

            {/* Content area */}
            <div className="flex flex-col flex-1">
              {showSessionModal ? (
                <div className="flex flex-1 items-center justify-center">
                  <SessionDetectedModal
                    inline
                    open
                    onLogout={handleLogout}
                    onCancel={handleCancel}
                  />
                </div>
              ) : (
                <>
                  {(!user || sessionCleared) && (
                    <RegisterForm
                      mode={mode}
                      setMode={setMode}
                      refToken={refToken}
                      onRegistered={() => setRegistered(true)}
                    />
                  )}
                  {registered && (
                    <div className="mt-6 mx-auto text-center text-sm text-gray-300">
                      Registrierung erfolgreich – Weiterleitung...
                    </div>
                  )}
                </>
              )}
            </div>
          </div>
        </div>
      </main>
    </PageLayout>
  )
}