import { redirect } from 'next/navigation'
import { createClient } from '@/lib/supabase/server'
import { getAppOrg } from '@/lib/org'
import { getEffectiveUser } from '@/lib/effective-user'
import { canTransfer } from '@/lib/permissions'
import { Nav } from '@/components/nav'

export default async function AppLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const supabase = await createClient()

  const {
    data: { user },
  } = await supabase.auth.getUser()
  if (!user) redirect('/login')

  const org = await getAppOrg(supabase)

  const effective = org
    ? await getEffectiveUser(supabase, org.id)
    : null

  if (!effective) redirect('/login')

  // Switcher candidates: every other user the super admin can see across
  // all orgs they're a member of. Two queries (no FK between
  // organization_members and profiles directly — both point at auth.users).
  let candidates: { id: string; email: string; full_name: string | null }[] = []
  if (effective.is_super_admin && !effective.is_viewing_as) {
    const { data: members } = await supabase
      .from('organization_members')
      .select('user_id')
      .returns<{ user_id: string }[]>()
    const otherIds = Array.from(
      new Set(
        (members ?? [])
          .map((m) => m.user_id)
          .filter((id) => id && id !== effective.real_user_id),
      ),
    )
    if (otherIds.length > 0) {
      const { data: profiles } = await supabase
        .from('profiles')
        .select('id, email, full_name')
        .in('id', otherIds)
        .returns<{ id: string; email: string; full_name: string | null }[]>()
      candidates = profiles ?? []
    }
  }

  // Comments for the bell in the nav (org-wide, last 50)
  type RawComment = {
    id: string
    body: string
    author_id: string | null
    created_at: string
    resolved_at: string | null
    resolved_by: string | null
  }
  const { data: rawComments } = org
    ? await supabase
        .from('comments')
        .select('id, body, author_id, created_at, resolved_at, resolved_by')
        .eq('org_id', org.id)
        .order('created_at', { ascending: false })
        .limit(50)
        .returns<RawComment[]>()
    : { data: null }

  const involvedIds = Array.from(
    new Set(
      (rawComments ?? [])
        .flatMap((c) => [c.author_id, c.resolved_by])
        .filter((v): v is string => !!v),
    ),
  )
  let commentProfiles: Record<string, { full_name: string | null; email: string }> = {}
  if (involvedIds.length > 0) {
    const { data: p } = await supabase
      .from('profiles')
      .select('id, full_name, email')
      .in('id', involvedIds)
      .returns<{ id: string; full_name: string | null; email: string }[]>()
    commentProfiles = Object.fromEntries(
      (p ?? []).map((row) => [row.id, { full_name: row.full_name, email: row.email }]),
    )
  }
  const nameFor = (id: string | null) => {
    if (!id) return 'Unknown'
    const p = commentProfiles[id]
    return p ? p.full_name || p.email : 'Unknown'
  }
  const commentItems = (rawComments ?? []).map((c) => ({
    id: c.id,
    body: c.body,
    author_id: c.author_id,
    author_name: nameFor(c.author_id),
    created_at: c.created_at,
    resolved_at: c.resolved_at,
    resolved_by_name: c.resolved_by ? nameFor(c.resolved_by) : null,
  }))
  const unresolvedCount = commentItems.filter((c) => !c.resolved_at).length

  return (
    <div className="app-shell">
      <Nav
        effective={effective}
        orgName={org?.name ?? null}
        switcherCandidates={candidates}
        canTransfer={canTransfer(effective)}
        commentItems={commentItems}
        unresolvedCommentCount={unresolvedCount}
        currentUserId={effective.real_user_id}
      />
      <div className="app-content">{children}</div>
    </div>
  )
}
