'use client'

import { useEffect, useRef, useState } from 'react'
import { ChevronDown, LogOut, UserRound } from 'lucide-react'
import { djangoUrl } from '@/lib/site-content'

async function logoutDashboard() {
  const csrfResponse = await fetch(djangoUrl('/csrf/'), { credentials: 'include', cache: 'no-store' })
  if (!csrfResponse.ok) throw new Error('Unable to prepare sign out. Refresh the page and try again.')
  const csrfPayload = await csrfResponse.json() as { csrfToken?: string }
  if (!csrfPayload.csrfToken) throw new Error('The sign-out security token is missing. Refresh the page and try again.')
  const response = await fetch(djangoUrl('/api/auth/logout/'), {
    method: 'POST',
    credentials: 'include',
    cache: 'no-store',
    headers: {
      Accept: 'application/json',
      'X-CSRFToken': csrfPayload.csrfToken,
    },
  })
  const payload = await response.json().catch(() => ({}))
  if (!response.ok) throw new Error(typeof payload.detail === 'string' ? payload.detail : 'Unable to sign out.')
  window.location.assign('/login')
}

export function DashboardLogoutButton({ className = '' }: { className?: string }) {
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState('')
  const signOut = async () => {
    if (busy) return
    setBusy(true)
    setError('')
    try {
      await logoutDashboard()
    } catch (reason) {
      setBusy(false)
      setError(reason instanceof Error ? reason.message : 'Unable to sign out.')
    }
  }
  return <span className="inline-flex flex-col items-end gap-1">
    <button type="button" onClick={signOut} disabled={busy} className={className || 'inline-flex items-center gap-2 font-bold text-[var(--teal)] disabled:cursor-wait disabled:opacity-60'}><LogOut size={14} /> {busy ? 'Signing out...' : 'Sign out'}</button>
    {error && <small className="max-w-64 text-right text-xs font-semibold text-red-700">{error}</small>}
  </span>
}

export function DashboardProfileMenu({ name, email, roles }: { name: string; email: string; roles: string[] }) {
  const [open, setOpen] = useState(false)
  const menuRef = useRef<HTMLDivElement>(null)
  const initials = name.split(' ').map((part) => part[0]).join('').slice(0, 2).toUpperCase() || 'RG'

  useEffect(() => {
    const closeOnOutsideClick = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) setOpen(false)
    }
    const closeOnEscape = (event: KeyboardEvent) => {
      if (event.key === 'Escape') setOpen(false)
    }
    document.addEventListener('mousedown', closeOnOutsideClick)
    document.addEventListener('keydown', closeOnEscape)
    return () => {
      document.removeEventListener('mousedown', closeOnOutsideClick)
      document.removeEventListener('keydown', closeOnEscape)
    }
  }, [])

  return <div ref={menuRef} className="relative">
    <button type="button" onClick={() => setOpen((current) => !current)} className="inline-flex items-center gap-2 rounded-full p-1.5 transition hover:bg-[var(--mist)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--teal)]" aria-label="Open profile menu" aria-haspopup="menu" aria-expanded={open}>
      <span className="grid size-10 place-items-center rounded-full bg-[var(--navy)] text-xs font-black text-white">{initials}</span>
      <ChevronDown size={16} className={'mr-1 text-[var(--ink-soft)] transition ' + (open ? 'rotate-180' : '')} aria-hidden="true" />
    </button>
    {open && <div role="menu" className="absolute right-0 top-full z-[120] mt-3 w-72 overflow-hidden rounded-2xl border border-[var(--line)] bg-white p-2 text-[var(--navy)] shadow-2xl">
      <div className="border-b border-[var(--line)] px-3 py-3"><p className="truncate text-sm font-bold">{name}</p><p className="mt-1 truncate text-xs text-[var(--ink-soft)]">{email}</p><p className="mt-1 truncate text-[11px] font-semibold text-[var(--teal)]">{roles.join(' - ') || 'Administrator'}</p></div>
      <a href={djangoUrl('/dashboard/account/')} role="menuitem" className="mt-2 flex items-center gap-3 rounded-xl px-3 py-3 text-sm font-semibold transition hover:bg-[var(--mist)]"><UserRound size={17} className="text-[var(--teal)]" /> Profile & account</a>
      <DashboardLogoutButton className="mt-1 flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left text-sm font-semibold text-red-700 transition hover:bg-red-50 disabled:cursor-wait disabled:opacity-60" />
    </div>}
  </div>
}
