import Link from "next/link"
import { redirect } from "next/navigation"
import { and, desc, eq, ne } from "drizzle-orm"
import { db } from "@/lib/db"
import { account_members, profiles } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { getAccountContext } from "@/lib/account"
import { PLAN_LIMITS } from "@/lib/stripe/plans"
import { TeamManager, type TeamMember } from "@/components/dashboard/team-manager"
import { Users } from "lucide-react"
import type { Plan } from "@/types"

export const metadata = { title: "Team Access" }

export default async function TeamSettingsPage() {
  const user = await getSessionUser()
  if (!user) redirect("/login")

  const ctx = await getAccountContext(user.id)

  // If the user is a MEMBER of someone else's account, show a read-only note
  // instead of management UI — they can't manage the owner's team.
  if (!ctx.isOwner) {
    const owner = await db.query.profiles.findFirst({
      where: eq(profiles.id, ctx.ownerId),
      columns: { full_name: true, company_name: true, email: true },
    })
    const ownerName =
      owner?.company_name || owner?.full_name || owner?.email || "another landlord"

    return (
      <div className="max-w-2xl space-y-6">
        <PageHeader />
        <div className="rounded-xl border border-white/[0.06] bg-[#16161f] p-6">
          <div className="flex items-start gap-3">
            <div className="rounded-lg bg-indigo-600/10 p-2">
              <Users className="h-5 w-5 text-indigo-400" />
            </div>
            <div>
              <p className="text-sm font-medium text-white">
                You&apos;re a {ctx.role} of {ownerName}&apos;s account
              </p>
              <p className="mt-1 text-sm text-white/50">
                You&apos;re working inside {ownerName}&apos;s portfolio.{" "}
                {ctx.canWrite
                  ? "You can view and edit their data."
                  : "You have read-only access to their data."}{" "}
                Only the account owner can manage team members.
              </p>
            </div>
          </div>
        </div>
      </div>
    )
  }

  // Owner: gate on their plan.
  const profile = await db.query.profiles.findFirst({
    where: eq(profiles.id, user.id),
    columns: { plan: true },
  })
  const plan = (profile?.plan ?? "starter") as Plan
  const hasTeamAccess = PLAN_LIMITS[plan].hasTeamAccess

  if (!hasTeamAccess) {
    return (
      <div className="max-w-2xl space-y-6">
        <PageHeader />
        <div className="rounded-xl border border-indigo-500/20 bg-indigo-600/5 p-8 text-center">
          <div className="mx-auto mb-4 w-fit rounded-xl bg-indigo-600/10 p-3">
            <Users className="h-6 w-6 text-indigo-400" />
          </div>
          <h3 className="text-base font-semibold text-white">Team access is a paid feature</h3>
          <p className="mx-auto mt-2 max-w-md text-sm text-white/50">
            Invite staff or co-managers to access your portfolio with the Landlord
            or Lifetime plan. Members can help manage your properties, and viewers
            get read-only access.
          </p>
          <Link
            href="/settings/billing"
            className="mt-6 inline-flex items-center justify-center rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white transition hover:bg-indigo-500"
          >
            Upgrade your plan
          </Link>
        </div>
      </div>
    )
  }

  const rows = await db
    .select({
      id: account_members.id,
      email: account_members.email,
      role: account_members.role,
      status: account_members.status,
    })
    .from(account_members)
    .where(and(eq(account_members.owner_id, user.id), ne(account_members.status, "revoked")))
    .orderBy(desc(account_members.created_at))

  const members: TeamMember[] = rows

  return (
    <div className="max-w-2xl space-y-6">
      <PageHeader />
      <TeamManager initialMembers={members} />
    </div>
  )
}

function PageHeader() {
  return (
    <div>
      <h2 className="text-lg font-semibold text-white">Team Access</h2>
      <p className="text-sm text-white/40">
        Invite people to help manage your property portfolio
      </p>
    </div>
  )
}
