'use client';

import Link from './account-link';

import {UserAvatar} from './user-avatar';
import {useEffect,useState,type ReactNode} from 'react';
import {Wallet,Bell,X,ChevronLeft,Settings2,ShieldCheck,LockKeyhole,CreditCard,LogOut,ArrowDownLeft,ArrowUpRight,History,ChartNoAxesCombined,Copy,Check,LoaderCircle,RefreshCw,Inbox,Ticket} from 'lucide-react';
import {Popover,PopoverTrigger,PopoverContent,PopoverTitle} from '@/components/ui/popover';
import type {CustomerUser} from '@/lib/auth-input';
import type {DashboardData} from '@/lib/dashboard';
import {localized} from '@/lib/catalog';
import type {Locale} from '@/lib/catalog';
import {accountCopy} from '@/lib/account-copy';
import {notificationCopy,notificationDate,notificationInboxHref,notificationPresentation} from '@/lib/customer-notifications';
import {dashboardNumber} from '@/lib/dashboard';
import {dashboardLabel} from '@/lib/dashboard-copy';
import '@/app/customer-notifications.css';

type Panel = 'profile'|'wallet'|'notifications';
type Address = {address:string;network:string};
type WalletState = {status:'loading'|'ready'|'unavailable'|'expired'|'error';addresses:Address[]};

function FutureRow({icon,label,soon,href,onNavigate}:{icon:ReactNode;label:string;soon:string;href?:string;onNavigate:()=>void}) {
  if(href)return <Link onNavigate={onNavigate} href={href} className="account-menu-row"><span className="account-row-icon">{icon}</span><span>{label}</span><ChevronLeft className="account-chevron" size={17}/></Link>;
  return <div className="account-menu-row is-unavailable" aria-disabled="true"><span className="account-row-icon">{icon}</span><span>{label}</span><small>{soon}</small></div>;
}

export function AccountMenu({user,locale,blocked=false,onAccount,onLogout,data,reload}:{user:CustomerUser;locale:Locale;blocked?:boolean;onAccount:()=>void;onLogout:()=>Promise<void>;data:DashboardData|null;reload:()=>Promise<void>}) {
  const copy=accountCopy(locale),notificationWords=notificationCopy(locale),dir=locale==='en'?'ltr':'rtl';
  const fullName=[data?.account.first_name,data?.account.last_name].filter(Boolean).join(' ')||user.name||user.username||copy.account;
  const [open,setOpen]=useState<Panel|null>(null);
  const [wallet,setWallet]=useState<WalletState>({status:'loading',addresses:[]}),[attempt,setAttempt]=useState(0);
  const [copied,setCopied]=useState(''),[copyError,setCopyError]=useState(false);
  const [loggingOut,setLoggingOut]=useState(false),[logoutError,setLogoutError]=useState(false);
  useEffect(()=>{if(blocked)setOpen(null)},[blocked]);
  useEffect(()=>{if(open==='notifications')void reload()},[open,reload]);
  useEffect(()=>{
    if(open!=='wallet')return;
    if(data){setWallet({status:'ready',addresses:data.wallets});return;}
    const controller=new AbortController();
    setWallet({status:'loading',addresses:[]});setCopied('');setCopyError(false);
    void (async()=>{
      try {
        const response=await fetch('/api/wallets',{cache:'no-store',credentials:'same-origin',signal:controller.signal});
        if(!response.ok){if(!controller.signal.aborted)setWallet({status:response.status===503?'unavailable':response.status===401?'expired':'error',addresses:[]});return;}
        const data=await response.json() as {wallets:Address[]};
        if(!Array.isArray(data.wallets)||data.wallets.some(w=>typeof w.address!=='string'||typeof w.network!=='string'))throw new Error('Invalid wallet response');
        if(!controller.signal.aborted)setWallet({status:'ready',addresses:data.wallets});
      }catch{if(!controller.signal.aborted)setWallet({status:'error',addresses:[]});}
    })();
    return()=>controller.abort();
  },[open,attempt,user.id,data]);
  useEffect(()=>{if(!copied)return;const timeout=setTimeout(()=>setCopied(''),2500);return()=>clearTimeout(timeout)},[copied]);
  const account=()=>{setOpen(null);onAccount()};
  const logout=async()=>{setLoggingOut(true);setLogoutError(false);try{await onLogout();setOpen(null)}catch{setLogoutError(true)}finally{setLoggingOut(false)}};
  const copyAddress=async(address:string)=>{setCopyError(false);try{await navigator.clipboard.writeText(address);setCopied(address)}catch{setCopyError(true)}};
  const emptyMessages=<div className="account-empty notifications-empty"><span className="account-empty-icon"><Inbox size={30}/></span><h3>{copy.emptyNotifications}</h3><p>{copy.notificationsBody}</p></div>;

  function panel(id:Panel,icon:ReactNode,label:string,children:ReactNode) {
    return <Popover key={id} open={!blocked&&open===id} onOpenChange={value=>setOpen(current=>value?id:current===id?null:current)}>
      <PopoverTrigger openOnHover delay={100} closeDelay={220} className={`account-trigger account-trigger-${id}`} aria-label={id==='notifications'&&data?.unread_count?`${label}؛ ${dashboardNumber(data.unread_count,locale,0)} ${notificationWords.newMessages}`:label} {...(id!=='notifications'?{nativeButton:false,render:<Link onNavigate={()=>setOpen(null)} href={id==='profile'?'/account':'/wallet'}/>}:{})}>
        {icon}{id==='notifications'&&!!data?.unread_count&&<span className="account-unread-count" aria-hidden="true">{dashboardNumber(Math.min(data.unread_count,99),locale,0)}{data.unread_count>99?'+':''}</span>}
      </PopoverTrigger>
      <PopoverContent className={`account-popover account-popover-${id}`} align="end" sideOffset={14} dir={dir} initialFocus={interaction=>interaction==='mouse'?false:true}>
        <div className="account-popover-heading"><PopoverTitle>{label}</PopoverTitle><button className="account-close" onClick={()=>setOpen(null)} aria-label={copy.close}><X size={17}/></button></div>
        {children}
      </PopoverContent>
    </Popover>;
  }

  return <><div className="customer-actions" role="group" aria-label={copy.account}>
    {panel('profile',<UserAvatar name={fullName} userId={user.id} path={data?.account.avatar_path} className="account-trigger-avatar"/>,copy.profile,<>
      <Link onNavigate={()=>setOpen(null)} href="/account" className="account-identity"><UserAvatar name={fullName} userId={user.id} path={data?.account.avatar_path} className="account-avatar"/><div><strong>{fullName}</strong><span>{copy.account}</span></div></Link>
      <dl className="account-contact">{user.username&&<div><dt>{copy.username}</dt><dd dir="ltr">{user.username}</dd></div>}<div><dt>{copy.email}</dt><dd dir={user.email?'ltr':dir}>{user.email||copy.notAdded}</dd></div><div><dt>{copy.phone}</dt><dd dir={user.phone?'ltr':dir}>{user.phone||copy.notAdded}</dd></div></dl>
      <div className="account-menu-group"><button className="account-menu-row" onClick={account}><span className="account-row-icon"><Settings2 size={21}/></span><span>{copy.accountDetails}</span><ChevronLeft className="account-chevron" size={17}/></button><Link onNavigate={()=>setOpen(null)} className="account-menu-row" href="/account/profile"><span className="account-row-icon"><ShieldCheck size={21}/></span><span>{copy.identity}</span><ChevronLeft className="account-chevron" size={17}/></Link><Link onNavigate={()=>setOpen(null)} className="account-menu-row" href="/account/banks"><span className="account-row-icon"><CreditCard size={21}/></span><span>{copy.banks}</span><ChevronLeft className="account-chevron" size={17}/></Link><Link onNavigate={()=>setOpen(null)} className="account-menu-row" href="/account/security"><span className="account-row-icon"><LockKeyhole size={21}/></span><span>{copy.security}</span><ChevronLeft className="account-chevron" size={17}/></Link></div>
      <div className="account-menu-group"><Link onNavigate={()=>setOpen(null)} className="account-menu-row" href="/account/tickets"><span className="account-row-icon"><Ticket size={21}/></span><span>{dashboardLabel('tickets',locale)}</span><ChevronLeft className="account-chevron" size={17}/></Link></div>
      <div className="account-menu-group"><button className="account-menu-row account-signout" onClick={logout} disabled={loggingOut}><span className="account-row-icon">{loggingOut?<LoaderCircle size={21} className="account-spinner"/>:<LogOut size={21}/>}</span><span>{loggingOut?copy.loggingOut:copy.logout}</span></button>{logoutError&&<p className="account-error" role="alert">{copy.logoutError}</p>}</div>
    </>)}
    {panel('wallet',<Wallet size={21}/>,copy.wallet,<>
      <Link onNavigate={()=>setOpen(null)} href="/wallet" className="account-wallet-heading"><span className="account-row-icon"><Wallet size={23}/></span><strong>{copy.addresses}</strong><ChevronLeft className="account-chevron" size={17}/></Link>
      <div className="account-wallet-content" aria-live="polite" aria-busy={wallet.status==='loading'}>
        {wallet.status==='loading'?<p className="account-loading"><LoaderCircle className="account-spinner" size={18}/>{copy.loading}</p>:wallet.status==='ready'&&wallet.addresses.length?<div className="account-address-list">{wallet.addresses.map(w=><div className="account-address" key={`${w.network}:${w.address}`}><span>{w.network}</span><code dir="ltr">{w.address}</code><button className="account-copy" onClick={()=>void copyAddress(w.address)} aria-label={`${copy.copy} ${w.network}`}>{copied===w.address?<Check size={15}/>:<Copy size={15}/>}<span>{copied===w.address?copy.copied:copy.copy}</span></button></div>)}</div>:<div className="account-wallet-state"><p>{wallet.status==='ready'?copy.noWallets:wallet.status==='unavailable'?copy.walletUnavailable:wallet.status==='expired'?copy.sessionExpired:copy.walletError}</p><span>{wallet.status==='ready'?copy.noWalletsBody:wallet.status==='unavailable'?copy.walletUnavailableBody:wallet.status==='error'?copy.walletErrorBody:null}</span>{wallet.status==='expired'?<button onClick={account}>{copy.accountDetails}</button>:wallet.status==='error'&&<button onClick={()=>setAttempt(n=>n+1)}><RefreshCw size={14}/>{copy.retry}</button>}</div>}
        {copyError&&<p className="account-error" role="alert">{copy.copyError}</p>}
      </div>
      <div className="account-menu-group account-transfer-grid"><FutureRow icon={<ArrowDownLeft size={21}/>} href="/wallet/deposit" label={`${copy.deposit} ${copy.toman}`} soon={copy.soon} onNavigate={()=>setOpen(null)}/><FutureRow icon={<ArrowUpRight size={21}/>} href="/wallet/withdraw" label={`${copy.withdraw} ${copy.toman}`} soon={copy.soon} onNavigate={()=>setOpen(null)}/><FutureRow icon={<ArrowDownLeft size={21}/>} href="/wallet/deposit?tab=token" label={`${copy.deposit} ${copy.token}`} soon={copy.soon} onNavigate={()=>setOpen(null)}/><FutureRow icon={<ArrowUpRight size={21}/>} href="/wallet/withdraw?tab=token" label={`${copy.withdraw} ${copy.token}`} soon={copy.soon} onNavigate={()=>setOpen(null)}/></div>
      <div className="account-menu-group"><FutureRow icon={<CreditCard size={21}/>} href="/account/banks" label={copy.banks} soon={copy.soon} onNavigate={()=>setOpen(null)}/><FutureRow icon={<History size={21}/>} href="/wallet/transactions" label={copy.transactions} soon={copy.soon} onNavigate={()=>setOpen(null)}/><FutureRow icon={<ChartNoAxesCombined size={21}/>} href="/wallet/orders" label={copy.trades} soon={copy.soon} onNavigate={()=>setOpen(null)}/></div>
    </>)}
    {panel('notifications',<Bell size={21}/>,copy.notifications,<><div className="account-notification-toolbar"><span>{copy.messages}{!!data?.unread_count&&<small className="account-message-counter">{dashboardNumber(data.unread_count,locale,0)} {notificationWords.unread}</small>}</span><Link onNavigate={()=>setOpen(null)} href="/account/notifications">{copy.showAll}<ChevronLeft className="account-chevron" size={15}/></Link></div>{data?.notifications.length?<div className="account-message-list">{data.notifications.slice(0,5).map(n=>{const presentation=notificationPresentation(n,locale);return <Link onNavigate={()=>setOpen(null)} href={notificationInboxHref(n.id)} key={n.id} className={`${n.read_at?'':'unread'} notification-${presentation.severity}`}><div className="account-message-meta"><span className="notification-status">{presentation.label}</span>{presentation.scope&&<span className="notification-status">{presentation.scope}</span>}<time dateTime={n.created_at}>{notificationDate(n.created_at,locale)}</time></div><strong>{localized(n.title,locale)}</strong><p>{presentation.noteLabel&&<b>{presentation.noteLabel}: </b>}{localized(n.body,locale)}</p>{presentation.context&&<small className="notification-review-context">{presentation.context}</small>}<small className="account-message-sender">{presentation.sender}</small></Link>})}</div>:emptyMessages}</>)}
  </div>
  </>;
}
