import { redirect } from 'next/navigation'
import { getProfile, getSessionUser } from '@/lib/auth'
import { createAdminClient } from '@/lib/supabase/admin'
import { AppShell } from '@/components/app/app-shell'
import { BackLink } from '@/components/app/back-link'
import {
  getCompanyContext, listClaimsAwaitingMyApproval, listCompanyAudit, listCompanyMembers,
} from '@/lib/data/companies'
import { CompanyHome } from './company-home'
import type { MemberView } from './company-console'
import type { BrokerPage, CompanyAuditEvent } from '@/types/db'

/**
 * Company page (Tasks 91 + 83): one screen for every state of "how you get
 * connected to your company" — not connected, request pending, requests
 * waiting for you as the corporate contact, approved agent, company admin.
 *
 * Nash (2026-09-08): "I tried to open my corporate profile… it's not doing
 * anything… Can we have the design done so we can present to the team before
 * we do the backend?" So the page never dead-ends: with migration 0013
 * missing it runs every state on demo data, and a signed-in user with no
 * company sees the three steps and the button instead of a note.
 *
 * Any approved member can open the corporate profile; only Company Owner /
 * Admin can edit (enforced again in the API).
 */
export default async function CompanyPage() {
  const user = await getSessionUser()
  if (!user) redirect('/login')
  const profile = (await getProfile())!
  const ctx = await getCompanyContext(user.id)

  // Requests waiting for THIS person because their account email is the
  // corporate email on file (Task 83).
  const approvals = ctx.available ? await listClaimsAwaitingMyApproval(user.email) : []

  let members: MemberView[] = []
  let audit: CompanyAuditEvent[] = []
  let brokerPage: BrokerPage | null = null

  if (ctx.available && ctx.company && ctx.membership?.status === 'approved') {
    const company = ctx.company
    const admin = createAdminClient()
    const [{ memberships, claims, profiles }, auditRows] = await Promise.all([
      listCompanyMembers(company.id),
      listCompanyAudit(company.id),
    ])
    audit = auditRows

    // The broker intake page this company owns (Task 94). Self-heal the link
    // once: a broker company whose owner already has a page adopts it.
    if (company.company_type === 'broker') {
      const linked = await admin.from('broker_pages').select('*').eq('company_id', company.id).maybeSingle()
      brokerPage = (linked.data ?? null) as BrokerPage | null
      if (!brokerPage) {
        const ownerIds = memberships
          .filter((m) => m.status === 'approved' && (m.role === 'company_owner' || m.role === 'company_admin'))
          .map((m) => m.user_id)
        if (ownerIds.length > 0) {
          const { data: owned } = await admin.from('broker_pages').select('*').in('owner_id', ownerIds).limit(1)
          const page = (owned?.[0] ?? null) as BrokerPage | null
          if (page) {
            await admin.from('broker_pages').update({ company_id: company.id }).eq('id', page.id)
            brokerPage = { ...page, company_id: company.id }
          }
        }
      }
    }

    members = memberships.map((m) => {
      const p = profiles.get(m.user_id)
      const claim = claims.find((c) => c.user_id === m.user_id) ?? null
      return {
        membership: m,
        claim,
        name: p?.full_name ?? '—',
        email: p?.email ?? '—',
        phone: p?.phone ?? null,
      }
    })
  }

  return (
    <AppShell profile={profile}>
      <main className="mx-auto max-w-4xl px-4 py-8">
        <BackLink />
        <CompanyHome
          available={ctx.available}
          me={{ email: user.email, name: user.name, role: user.role }}
          company={ctx.company}
          membership={ctx.membership}
          claim={ctx.claim}
          members={members}
          audit={audit}
          brokerPage={brokerPage}
          approvals={approvals}
          internal={user.internal}
        />
      </main>
    </AppShell>
  )
}
