import { auth } from '@/lib/auth'
import { prisma } from '@innungsapp/shared'
import { headers } from 'next/headers'
import Link from 'next/link'
import { redirect } from 'next/navigation'

export default async function GlobalDashboardRedirect() {
    const headerList = await headers()
    const host = headerList.get('host') || ''
    const session = await auth.api.getSession({ headers: headerList })

    if (!session?.user) {
        redirect('/login')
    }

    // Superadmin logic
    const superAdminEmail = process.env.SUPERADMIN_EMAIL || 'superadmin@innungsapp.de'
    const isSuperAdmin = session.user.email === superAdminEmail || session.user.role === 'admin'

    if (isSuperAdmin) {
        redirect('/superadmin')
    }

    const userRoles = await prisma.userRole.findMany({
        where: { userId: session.user.id, role: 'admin' },
        include: {
            org: {
                select: { id: true, name: true, slug: true },
            },
        },
        orderBy: { createdAt: 'asc' },
    })

    if (userRoles.length === 1) {
        const slug = userRoles[0].org.slug
        const protocol = host.includes('localhost') ? 'http' : 'https'

        // Construct the subdomain URL
        let newHost = host
        if (host.includes('localhost')) {
            const port = host.includes(':') ? `:${host.split(':')[1]}` : ''
            newHost = `${slug}.localhost${port}`
        } else {
            // Assumes domain.tld
            const parts = host.split('.')
            if (parts.length === 2) {
                newHost = `${slug}.${host}`
            } else if (parts.length > 2) {
                newHost = `${slug}.${parts.slice(-2).join('.')}`
            }
        }

        redirect(`${protocol}://${newHost}/dashboard`)
    }

    const getOrgUrl = (slug: string, currentHost: string) => {
        const protocol = currentHost.includes('localhost') ? 'http' : 'https'
        let newHost = currentHost
        if (currentHost.includes('localhost')) {
            const port = currentHost.includes(':') ? `:${currentHost.split(':')[1]}` : ''
            newHost = `${slug}.localhost${port}`
        } else {
            const parts = currentHost.split('.')
            newHost = parts.length >= 2 ? `${slug}.${parts.slice(-2).join('.')}` : `${slug}.${currentHost}`
        }
        return `${protocol}://${newHost}/dashboard`
    }

    return (
        <div className="min-h-screen bg-gray-50 flex flex-col items-center justify-center p-4">
            <div className="bg-white border rounded-xl p-8 max-w-md w-full text-center shadow-sm">
                <h1 className="text-xl font-bold text-gray-900 mb-2">
                    {userRoles.length > 1 ? 'Bitte Innung auswählen' : 'Kein Mandant zugeordnet'}
                </h1>

                {userRoles.length > 1 ? (
                    <div className="space-y-2 mb-6">
                        {userRoles.map((userRole) => (
                            <Link
                                key={userRole.org.id}
                                href={getOrgUrl(userRole.org.slug, host)}
                                className="block w-full rounded-lg border border-gray-200 px-4 py-3 text-sm text-gray-700 hover:border-brand-500 hover:text-brand-700 transition-colors"
                            >
                                {userRole.org.name}
                            </Link>
                        ))}
                    </div>
                ) : (
                    <p className="text-gray-500 mb-6 text-sm">
                        Ihr Konto hat aktuell keinen Admin-Zugriff auf eine Innung.
                    </p>
                )}

                <form action={async () => {
                    'use server'
                    const { auth } = await import('@/lib/auth')
                    const { headers } = await import('next/headers')
                    await auth.api.signOut({ headers: await headers() })
                    redirect('/login')
                }}>
                    <button type="submit" className="text-sm font-medium text-brand-600 hover:text-brand-700">
                        Abmelden
                    </button>
                </form>
            </div>
        </div>
    )
}
