'use client'

import { useEffect, useState } from 'react'
import { useRouter, useParams } from 'next/navigation'
import { useAuth } from '@/components/providers/auth-provider'
import { Loader2 } from 'lucide-react'
import { LogoRound } from '@/components/ui/logo'

interface TenantInfo {
  name: string
  slug: string
  logoUrl: string | null
}

export default function TenantPortalPage() {
  const { slug } = useParams<{ slug: string }>()
  const { user, loading } = useAuth()
  const router = useRouter()
  const [error, setError] = useState<string | null>(null)
  const [tenant, setTenant] = useState<TenantInfo | null>(null)

  useEffect(() => {
    // Skip known non-tenant routes
    const reserved = ['app', 'admin', 'login', 'register', 'api', 'forgot-password', 'reset-password', 'spenden', 'demo']
    if (reserved.includes(slug)) {
      return
    }

    // Fetch tenant info (public)
    fetch(`/api/tenants/by-slug/${slug}`)
      .then(async res => {
        const data = await res.json()
        if (res.ok && data?.tenant) {
          setTenant(data.tenant)
        } else if (res.status === 403 && data?.reason === 'suspended') {
          // Tenant exists but is suspended
          if (data.tenant) setTenant(data.tenant)
          setError('Dieser Mandant wurde gesperrt. Bitte kontaktieren Sie den Administrator für weitere Informationen.')
        } else {
          setError('Mandant nicht gefunden.')
        }
      })
      .catch(() => setError('Fehler beim Laden.'))
  }, [slug])

  useEffect(() => {
    const reserved = ['app', 'admin', 'login', 'register', 'api', 'forgot-password', 'reset-password', 'spenden', 'demo']
    if (reserved.includes(slug)) return
    if (loading || !tenant) return

    if (!user) {
      // Not logged in → redirect to login with slug context
      router.push(`/login?redirect=/${slug}&tenant=${slug}`)
      return
    }

    // Check if user belongs to this tenant
    if (user.tenantSlug === slug) {
      router.push('/app')
    } else {
      setError('Sie haben keinen Zugang zu diesem Mandanten.')
    }
  }, [slug, user, loading, router, tenant])

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 px-4">
        <div className="text-center">
          {tenant?.logoUrl ? (
            <img src={tenant.logoUrl} alt={tenant.name} className="w-20 h-20 object-contain mx-auto mb-4 rounded-lg" />
          ) : (
            <LogoRound size={56} className="mx-auto mb-4" />
          )}
          <h1 className="text-xl font-bold text-white mb-2">Zugang verweigert</h1>
          <p className="text-gray-400 mb-6">{error}</p>
          <button onClick={() => router.push(`/login?tenant=${slug}`)} className="text-red-400 hover:text-red-300 text-sm underline">
            Zur Anmeldung
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900">
      {tenant?.logoUrl ? (
        <div className="flex flex-col items-center gap-4">
          <img src={tenant.logoUrl} alt={tenant.name} className="w-20 h-20 object-contain rounded-lg animate-pulse" />
          <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
        </div>
      ) : (
        <Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
      )}
    </div>
  )
}
