import type React from "react"
import { cookies } from "next/headers"
import { redirect } from "next/navigation"
import { AppSidebar } from "@/components/layout/app-sidebar"
import { AppHeader } from "@/components/layout/app-header"
import type { UserMenuUser } from "@/components/layout/user-menu"
import { NotificationListener } from "@/components/NotificationListener"
import i18n from "@/lib/i18n";

function decodeCookieValue(value: string) {
  try {
    return decodeURIComponent(value)
  } catch {
    return value
  }
}

function parseJson(value?: string | null) {
  if (!value) return null

  const candidates = [value, decodeCookieValue(value)]
  for (const candidate of candidates) {
    try {
      return JSON.parse(candidate)
    } catch {
      // Try the next representation.
    }
  }

  return null
}

function parseFastApiSession(value?: string | null) {
  if (!value) return null

  try {
    const decoded = Buffer.from(value, "base64").toString("utf8")
    return JSON.parse(decoded)
  } catch {
    return null
  }
}

function parseJwtPayload(value?: string | null) {
  if (!value) return null

  try {
    const payload = value.split(".")[1]
    if (!payload) return null

    const normalized = payload.replace(/-/g, "+").replace(/_/g, "/")
    const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=")
    return JSON.parse(Buffer.from(padded, "base64").toString("utf8"))
  } catch {
    return null
  }
}

function applyUser(headerUser: UserMenuUser, user: any) {
  if (!user) return

  const roles = Array.isArray(user.roles) ? user.roles : []
  const permissions = Array.isArray(user.permissions) ? user.permissions : []
  const email = user.email || user.sub || user.username || ""
  const name = user.name || user.full_name || user.full_name_ar || user.fullName || ""
  const role = user.role || roles[0]?.code || user.user_type || user.userType || "operations_admin"

  headerUser.id = user.id || user.user_id || user.uid || ""
  headerUser.fullName = name || email?.split("@")[0] || i18n.t('app.admin.layout.text_2')
  headerUser.role = role
  headerUser.email = email
  headerUser.roles = roles
  headerUser.userType = user.user_type || user.userType || ""
  headerUser.status = user.status || ""
  headerUser.permissionsCount = permissions.length
}

export default async function AdminLayout({ children }: { children: React.ReactNode }) {
  const cookieStore = await cookies()
  const token = cookieStore.get("auth_token")?.value
  const userCookie = cookieStore.get("auth_user")?.value
  const sessionCookie = cookieStore.get("fastapi-session")?.value

  if (!token) {
    redirect("/login")
  }

  const headerUser: UserMenuUser = {
    fullName: i18n.t('app.admin.layout.text_1'),
    email: "",
    role: "operations_admin",
    roles: [],
    permissionsCount: 0,
  }

  const userFromCookie = parseJson(userCookie)
  const session = parseFastApiSession(sessionCookie)
  const userFromSession = session?.user
  const userFromToken = parseJwtPayload(token)

  applyUser(headerUser, userFromCookie || userFromSession || userFromToken)

  return (
    <div className="min-h-screen bg-background">
      <NotificationListener />
      <AppSidebar />
      <div className="ltr:lg:ml-64 rtl:lg:mr-64">
        <AppHeader user={headerUser} />
        <main className="px-4 md:px-6 lg:px-8 py-6">{children}</main>
      </div>
    </div>
  )
}
