import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { SettingsForm, type SettingRow } from '@/components/console/settings-form'
import { KeyValue, PageHeader, Panel, PanelBody, PanelHeader } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { prisma } from '@/lib/db'
import { getI18n } from '@/lib/i18n/server'
import { getGridSnapshot } from '@/lib/services/grid-service'

export const metadata: Metadata = { title: 'Settings' }
export const dynamic = 'force-dynamic'

export default async function SettingsPage() {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()

  if (!user?.permissions.has('settings.read')) return <PermissionGate />

  const [settings, snapshot] = await Promise.all([
    prisma.appSetting.findMany({ orderBy: [{ groupKey: 'asc' }, { key: 'asc' }] }),
    getGridSnapshot(),
  ])

  const rows: SettingRow[] = settings.map((setting) => ({
    key: setting.key,
    value: setting.value,
    valueType: setting.valueType,
    groupKey: setting.groupKey,
    label: setting.label,
    labelAr: setting.labelAr,
    description: setting.description,
    descriptionAr: setting.descriptionAr,
    minValue: setting.minValue,
    maxValue: setting.maxValue,
  }))

  // Shows the current weights applied to the asset that most depends on them.
  const highest = [...snapshot.assets].sort((a, b) => b.risk.score - a.risk.score)[0]
  const preview = highest
    ? { assetCode: highest.profile.code, riskScore: highest.risk.score }
    : null

  return (
    <>
      <PageHeader title={t('settings.title')} subtitle={t('settings.subtitle')} />

      <div className="grid gap-6 xl:grid-cols-[1fr_300px]">
        <SettingsForm
          settings={rows}
          canManage={user.permissions.has('settings.manage')}
          preview={preview}
        />

        <Panel className="self-start">
          <PanelHeader title={t('settings.profile')} />
          <PanelBody>
            <dl className="divide-y divide-border/60">
              <KeyValue label={t('common.signedInAs')} value={locale === 'ar' ? user.nameAr : user.name} />
              <KeyValue label={t('auth.email')} value={user.email} mono />
              <KeyValue label={t('users.columns.employeeId')} value={user.employeeId} mono />
              <KeyValue
                label={t('users.columns.department')}
                value={locale === 'ar' ? user.departmentAr : user.department}
              />
              <KeyValue
                label={t('users.columns.roles')}
                value={user.roles.map((role) => t(`role.${role}`)).join(', ')}
              />
              <KeyValue
                label={t('roles.permissionCount', { count: user.permissions.size })}
                value={String(user.permissions.size)}
                mono
              />
            </dl>

            <p className="mt-4 text-[11px] leading-relaxed text-text-faint">
              {t('settings.preferredLanguage')} — {t('common.language')}
            </p>
          </PanelBody>
        </Panel>
      </div>
    </>
  )
}
