import { cookies } from 'next/headers'
import { DashboardWorkspace, type ManagementData } from '@/components/dashboard-workspace'
import type { DashboardData } from '@/components/admin-dashboard'
import { djangoUrl } from '@/lib/site-content'

function managementResource(path: string[]) {
  if (path[0] === 'content' && path[1]) {
    return ['content', path[1], path[2] && path[2] !== 'new' && path[2] !== 'edit' ? path[2] : ''].filter(Boolean).join('/')
  }
  if (path[0] === 'messages') return ['messages', path[1] && path[1] !== 'edit' ? path[1] : ''].filter(Boolean).join('/')
  if (path[0] === 'requests') return ['requests', path[1], path[2]].filter(Boolean).join('/')
  if (path[0] === 'users') return ['users', path[1] && path[1] !== 'new' && path[1] !== 'edit' ? path[1] : ''].filter(Boolean).join('/')
  if (path[0] === 'settings') return 'settings'
  return ''
}

export default async function DashboardManagementPage({ params }: { params: Promise<{ path: string[] }> }) {
  const { path } = await params
  const resource = managementResource(path)
  const cookieHeader = (await cookies()).toString()
  let dashboard: DashboardData | null = null
  let management: ManagementData | null = null
  let initialError = ''

  try {
    const headers = cookieHeader ? { cookie: cookieHeader } : undefined
    const responses = await Promise.all([
      fetch(djangoUrl('/api/dashboard/?range=7'), { headers, cache: 'no-store', signal: AbortSignal.timeout(8000) }),
      fetch(djangoUrl('/api/dashboard/manage/' + resource + '/'), { headers, cache: 'no-store', signal: AbortSignal.timeout(8000) }),
    ])
    if (responses[0].ok) dashboard = await responses[0].json() as DashboardData
    if (responses[1].ok) management = await responses[1].json() as ManagementData
    if (!responses[0].ok || !responses[1].ok) {
      initialError = responses[0].status === 401 || responses[1].status === 401
        ? ''
        : 'You do not have permission to open this dashboard area.'
    }
  } catch {
    initialError = 'The Django dashboard API is unavailable.'
  }

  return <DashboardWorkspace path={path} resource={resource} initialDashboard={dashboard} initialData={management} initialError={initialError} />
}
