"use client"

import { useState, useRef, useEffect } from "react"
import type { ReactNode } from "react"
import { BadgeCheck, ChevronDown, Fingerprint, KeyRound, LogOut, Mail, Shield, UserRound } from "lucide-react"
import { useAuth } from "@/contexts/auth-context"
import { initialsOf } from "@/lib/format"
import i18n from "@/lib/i18n";

type MenuRole = {
  id?: string
  code?: string
  name_ar?: string
  name_en?: string | null
}

export type UserMenuUser = {
  id?: string
  fullName: string
  email: string
  role: string
  roles?: MenuRole[]
  userType?: string
  status?: string
  permissionsCount?: number
}

const ROLE_LABELS: Record<string, string> = {
  super_admin: i18n.t('components.layout.user-menu.text_1'),
  operations_admin: i18n.t('components.layout.user-menu.text_2'),
  compliance_officer: i18n.t('components.layout.user-menu.text_3'),
  finance_admin: i18n.t('components.layout.user-menu.text_4'),
  support_agent: i18n.t('components.layout.user-menu.text_5'),
}

const STATUS_LABELS: Record<string, string> = {
  active: i18n.t('components.layout.user-menu.text_10'),
  suspended: i18n.t('components.layout.user-menu.text_11'),
  blocked: i18n.t('components.layout.user-menu.text_12'),
  archived: i18n.t('components.layout.user-menu.text_13'),
  pending: i18n.t('components.layout.user-menu.text_14'),
}

const USER_TYPE_LABELS: Record<string, string> = {
  admin: i18n.t('components.layout.user-menu.text_15'),
  employee: i18n.t('components.layout.user-menu.text_16'),
  customer: i18n.t('components.layout.user-menu.text_17'),
}

function normalizeKey(value?: string) {
  return (value || "").trim().toLowerCase()
}

function roleLabel(role?: string, roles: MenuRole[] = []) {
  const key = normalizeKey(role)
  const matchedRole = roles.find((item) => normalizeKey(item.code) === key) || roles[0]

  if (matchedRole) {
    const localizedName = i18n.language === "ar" ? matchedRole.name_ar : matchedRole.name_en
    return localizedName || matchedRole.name_ar || matchedRole.name_en || ROLE_LABELS[normalizeKey(matchedRole.code)] || matchedRole.code || ROLE_LABELS[key]
  }

  return ROLE_LABELS[key] || role || i18n.t('components.layout.user-menu.text_7')
}

function InfoRow({
  icon,
  label,
  value,
}: {
  icon: ReactNode
  label: string
  value: ReactNode
}) {
  return (
    <div className="flex items-start gap-2.5 rounded-lg border border-border/70 bg-muted/30 px-3 py-2">
      <span className="mt-0.5 text-muted-foreground">{icon}</span>
      <div className="min-w-0 flex-1">
        <p className="text-[10.5px] font-medium text-muted-foreground">{label}</p>
        <div className="text-[12.5px] font-semibold text-foreground break-words">{value}</div>
      </div>
    </div>
  )
}

export function UserMenu({ user }: { user: UserMenuUser }) {
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)
  const { user: authUser } = useAuth()
  const menuUser: UserMenuUser = authUser
    ? {
        id: authUser.id,
        fullName: authUser.name || authUser.email?.split("@")[0] || user.fullName,
        email: authUser.email || user.email,
        role: authUser.role || user.role,
        roles: authUser.roles || user.roles,
        userType: authUser.user_type || user.userType,
        status: authUser.status || user.status,
        permissionsCount: Array.isArray(authUser.permissions) ? authUser.permissions.length : user.permissionsCount,
      }
    : user

  const fullName = menuUser.fullName || menuUser.email || i18n.t('components.layout.user-menu.text_6')
  const roleName = roleLabel(menuUser.role, menuUser.roles)
  const status = STATUS_LABELS[normalizeKey(menuUser.status)] || menuUser.status || i18n.t('components.layout.user-menu.text_18')
  const userType = USER_TYPE_LABELS[normalizeKey(menuUser.userType)] || menuUser.userType || i18n.t('components.layout.user-menu.text_18')
  const permissionText = typeof menuUser.permissionsCount === "number"
    ? i18n.t('components.layout.user-menu.text_19', { count: menuUser.permissionsCount })
    : i18n.t('components.layout.user-menu.text_18')

  useEffect(() => {
    function onClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false)
    }
    document.addEventListener("mousedown", onClick)
    return () => document.removeEventListener("mousedown", onClick)
  }, [])

  return (
    <div className="relative" ref={ref}>
      <button
        onClick={() => setOpen((v) => !v)}
        className="flex items-center gap-2.5 rounded-lg hover:bg-muted px-2 py-1 transition"
      >
        <div className="flex h-9 w-9 items-center justify-center rounded-full bg-gradient-to-br from-gold-400 to-gold-600 text-white text-[12.5px] font-bold shadow-sm">
          {initialsOf(fullName || menuUser.email)}
        </div>
        <div className="hidden md:flex flex-col text-right leading-tight">
          <span className="text-[12.5px] font-semibold text-foreground">{fullName}</span>
          <span className="text-[10.5px] text-muted-foreground">{roleName}</span>
        </div>
        <ChevronDown className="hidden md:block h-4 w-4 text-muted-foreground" />
      </button>

      {open && (
        <div className="absolute top-full left-0 mt-2 w-80 rounded-xl border border-border bg-card shadow-lg overflow-hidden z-50">
          <div className="p-3 border-b border-border">
            <div className="flex items-start gap-3">
              <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-gold-400 to-gold-600 text-white text-sm font-bold shadow-sm">
                {initialsOf(fullName || menuUser.email)}
              </div>
              <div className="min-w-0 flex-1">
                <div className="text-[13px] font-semibold text-foreground truncate">{fullName}</div>
                <div className="text-[11.5px] text-muted-foreground truncate">{menuUser.email || i18n.t('components.layout.user-menu.text_18')}</div>
              </div>
            </div>
            <div className="mt-2 inline-flex items-center gap-1.5 text-[11px] px-2 py-0.5 rounded-full bg-gold-50 text-gold-800 border border-gold-200">
              <Shield className="h-3 w-3" />
              {roleName}
            </div>
          </div>
          <div className="grid gap-2 p-3 border-b border-border">
            <InfoRow icon={<Mail className="h-4 w-4" />} label={i18n.t('components.layout.user-menu.text_20')} value={menuUser.email || i18n.t('components.layout.user-menu.text_18')} />
            <InfoRow icon={<UserRound className="h-4 w-4" />} label={i18n.t('components.layout.user-menu.text_21')} value={userType} />
            <InfoRow icon={<BadgeCheck className="h-4 w-4" />} label={i18n.t('components.layout.user-menu.text_22')} value={status} />
            <InfoRow icon={<KeyRound className="h-4 w-4" />} label={i18n.t('components.layout.user-menu.text_23')} value={permissionText} />
            {menuUser.id ? (
              <InfoRow icon={<Fingerprint className="h-4 w-4" />} label={i18n.t('components.layout.user-menu.text_24')} value={<span className="font-mono text-[11px]">{menuUser.id}</span>} />
            ) : null}
          </div>
          <div className="p-1">
            <form action="/auth/logout" method="post">
              <button
                type="submit"
                className="w-full flex items-center gap-2.5 px-3 py-2 text-[12.5px] text-red-600 hover:bg-red-50 rounded-lg transition"
              >
                <LogOut className="h-4 w-4" />
                {i18n.t('components.layout.user-menu.text_9')}</button>
            </form>
          </div>
        </div>
      )}
    </div>
  )
}
