import { redirect } from "next/navigation"
import { auth } from "@/lib/auth"
import { getChannelsAction } from "@/lib/actions/channel"
import { getAccountsAction } from "@/lib/actions/account"
import { AppSidebar } from "@/components/app-sidebar"
import { AppHeader } from "@/components/app-header"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { ChannelsView } from "./channels-view"

export default async function ChannelsPage() {
  const session = await auth()

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

  const user = session.user
  const userName = user.name || "Fluxent 用户"
  const userEmail = user.email || ""
  const userAvatar = user.image || null

  const [channelsRes, accountsRes] = await Promise.all([
    getChannelsAction(),
    getAccountsAction(),
  ])

  const initialChannels =
    channelsRes.success && channelsRes.data ? channelsRes.data : []
  const initialAccounts =
    accountsRes.success && accountsRes.data ? accountsRes.data : []

  return (
    <SidebarProvider>
      <AppSidebar
        user={{
          name: userName,
          email: userEmail,
          avatar: userAvatar,
        }}
      />
      <SidebarInset>
        <AppHeader title="支付渠道" />

        <ChannelsView
          key={JSON.stringify([initialChannels, initialAccounts])}
          initialChannels={initialChannels}
          initialAccounts={initialAccounts}
        />
      </SidebarInset>
    </SidebarProvider>
  )
}
