"use client"

import { UserRound } from "lucide-react"
import { CompteAvatarField } from "@/components/compte/compte-avatar-field"
import { CompteAuthentikPanel } from "@/components/compte/compte-authentik-panel"
import { CompteSettingsCard } from "@/components/compte/compte-settings-card"
import { SettingsSectionHeader } from "@/components/gmail/settings/settings-section-header"
import { SettingsSyncBanner } from "@/components/gmail/settings/settings-sync-banner"
import { useCurrentUser } from "@/lib/api/hooks/use-current-user"
import { useChromeIdentity } from "@/lib/hooks/use-chrome-identity"

const ROLE_LABELS: Record<string, string> = {
  admin: "Administrateur",
  user: "Utilisateur",
  guest: "Invité",
  suspended: "Suspendu",
}

export function ComptePersonalInfoSection() {
  const identity = useChromeIdentity()
  const { data: user, isFetching, isError, refetch } = useCurrentUser()

  const name = user?.name || identity?.name || "—"
  const email = user?.email || identity?.email || "—"

  return (
    <>
      <SettingsSectionHeader
        title="Informations personnelles"
        description="Informations de votre compte Ulti, partagées par toutes les applications de la suite."
      />
      <SettingsSyncBanner
        isFetching={isFetching}
        isError={isError}
        onRetry={() => refetch()}
      />

      <div className="space-y-4">
        <CompteAvatarField avatarUrl={user?.avatar_url} name={name} email={email} />

        <CompteSettingsCard className="overflow-hidden p-0">
          <InfoRow label="Nom" value={name} />
          <InfoRow label="Adresse e-mail" value={email} />
          <InfoRow label="Identifiant" value={user?.sub ?? "—"} mono />
          {user ? (
            <InfoRow label="Rôle" value={ROLE_LABELS[user.role] ?? user.role} />
          ) : null}
          {user?.groups?.length ? (
            <InfoRow label="Groupes" value={user.groups.join(", ")} />
          ) : null}
        </CompteSettingsCard>

        <CompteAuthentikPanel
          icon={<UserRound className="size-5" aria-hidden />}
          title="Modifier le profil"
          description="Nom, adresse e-mail et locale selon les droits définis par votre organisation."
          tab="details"
          actionLabel="Modifier le profil"
        />
      </div>
    </>
  )
}

function InfoRow({
  label,
  value,
  mono = false,
}: {
  label: string
  value: string
  mono?: boolean
}) {
  return (
    <div className="flex flex-col gap-0.5 border-b border-border px-4 py-3 last:border-b-0 sm:flex-row sm:items-center sm:gap-4">
      <span className="w-40 shrink-0 text-xs font-medium uppercase tracking-wide text-muted-foreground">
        {label}
      </span>
      <span
        className={
          mono
            ? "min-w-0 break-all font-mono text-xs text-foreground"
            : "min-w-0 truncate text-sm text-foreground"
        }
      >
        {value}
      </span>
    </div>
  )
}
