'use client';
import {useState} from 'react';
import {ArrowDownLeft,ArrowUpRight,ArrowLeft,ArrowLeftRight,Coins,CreditCard,Eye,EyeOff,History,Search,Wallet,Link2,Plus,ChevronDown} from 'lucide-react';
import {useSite} from './site-shell';
import {useDashboardCatalog} from './dashboard-catalog-context';
import Link from './account-link';
import {WalletActionLink} from './wallet-action-link';
import {WalletAddressManagement} from './wallet-address-management';
import {DemoBalance} from './wallet-funding';
import {FundingHistory} from './funding-review';
import {Switch} from './ui/switch';
import {portfolioSummary} from '@/lib/portfolio-summary';
import {cashWallet,isCashPosition} from '@/lib/cash-wallet';
import {dashboardNumber,decimalUnits,unitsDecimal,type DashboardData,type Preferences} from '@/lib/dashboard';
import {localized} from '@/lib/catalog';
import {rialToToman} from '@/lib/trade';

const colors=['#20bfa9','#5388ed','#a18be8','#deb56d','#86a1ad'];
export function WalletDashboard({data,prefs,busy,savePref,onAddBank}:{data:DashboardData;prefs:Preferences;busy:boolean;savePref:(p:Partial<Preferences>)=>Promise<boolean>;onAddBank:()=>void}){
 const {locale}=useSite(),catalog=useDashboardCatalog(),[search,setSearch]=useState('');
 const summary=portfolioSummary(data.positions,prefs.currency),cash=cashWallet(data.positions),hidden=prefs.hide_balances;
 const number=(v:string|number|null,decimals=4)=>hidden?'••••••':dashboardNumber(v,locale,decimals);
 const total=summary.total===null?null:prefs.currency==='TMN'?rialToToman(summary.total):unitsDecimal(summary.total);
 const unit=prefs.currency==='TMN'?'تومان':'USDT';
 const gradient=summary.segments.length&&!hidden?`conic-gradient(${summary.segments.map((s,i)=>`${colors[i]} ${s.start}% ${s.end}%`).join(',')})`:undefined;
 const positions=data.positions.filter(p=>(p.asset_symbol+' '+localized(p.asset_name,locale)).toLowerCase().includes(search.trim().toLowerCase())&&(!prefs.hide_small_assets||p.value_rial===null||BigInt(p.value_rial)>=BigInt(100000)));
 const cashText=(value:bigint|undefined)=>number(value===undefined?null:rialToToman(value),1);
 return <div className="unified-wallet">
  <section className="dash-card wallet-home-summary" aria-label="کیف پول اصلی">
   <div className="wallet-home-balance">
    <header><span className="wallet-home-symbol"><Wallet size={26}/></span><div><h2>کیف پول شما</h2><p>موجودی نقدی، کوین‌ها و توکن‌ها در یک نگاه</p></div><Link href="/wallet/transactions" className="dash-icon-button" aria-label="تاریخچه تراکنش‌ها"><History size={20}/></Link></header>
    <div className="wallet-home-value-label"><span>ارزش کل دارایی‌ها</span><button className="dash-icon-button" disabled={busy} onClick={()=>void savePref({hide_balances:!hidden})} aria-label={hidden?'نمایش موجودی':'پنهان کردن موجودی'}>{hidden?<EyeOff size={18}/>:<Eye size={18}/>}</button><div className="wallet-home-currency" role="group" aria-label="واحد نمایش ارزش دارایی">{(['TMN','USDT'] as const).map(currency=><button key={currency} aria-pressed={currency===prefs.currency} disabled={busy} onClick={()=>void savePref({currency})}>{currency==='TMN'?'تومان':'تتر'}</button>)}</div></div>
    <div className="wallet-home-total"><b>{number(total,2)}</b><span>{unit}</span></div>
    <p className="wallet-home-note">{summary.status==='incomplete'?'ارزش بعضی از دارایی‌ها هنوز در دسترس نیست.':'بر اساس آخرین موجودی و ارزش‌گذاری ثبت‌شده'}</p>
    <div className="wallet-home-cash"><div><span>تومان در دسترس</span><strong>{cashText(cash?.availableRial)} <small>تومان</small></strong></div><div><span>تومان رزروشده</span><strong>{cashText(cash?.lockedRial)} <small>تومان</small></strong></div></div>
   </div>
   <div className="wallet-home-allocation"><div className="wallet-home-ring" style={{background:gradient}}><div><Coins size={24}/><span>دارایی با موجودی</span><strong>{hidden?'•••':dashboardNumber(data.positions.filter(p=>decimalUnits(p.quantity)>BigInt(0)).length,locale,0)}</strong></div></div><div className="wallet-home-legend">{!hidden&&summary.segments.map((s,i)=><span key={s.key}><i style={{background:colors[i]}}/>{s.symbol==='other'?'سایر':s.symbol}</span>)}</div></div>
   <nav className="wallet-home-actions" aria-label="عملیات کیف پول">
    <Link href="/wallet/deposit"><span><ArrowDownLeft size={24}/></span>واریز تومان</Link>
    <Link href="/wallet/deposit?tab=token"><span><Coins size={24}/></span>واریز کوین</Link>
    <WalletActionLink action="withdrawal" href="/wallet/withdraw"><span><ArrowUpRight size={24}/></span>برداشت</WalletActionLink>
    <WalletActionLink action="trading" href="/#market"><span><ArrowLeftRight size={24}/></span>خرید و فروش</WalletActionLink>
    <button onClick={onAddBank}><span><CreditCard size={24}/></span>افزودن حساب بانکی</button>
    <Link href="#wallet-addresses"><span><Link2 size={24}/></span>آدرس‌های والت</Link>
   </nav>
  </section>
  <section className="dash-card wallet-home-assets" aria-labelledby="wallet-assets-title"><div className="dash-card-heading"><div><h2 id="wallet-assets-title">دارایی‌ها و توکن‌های شما</h2><p className="wallet-home-note">موجودی، مبلغ رزروشده و عملیات هر دارایی</p></div><label className="dash-search"><Search size={17}/><input placeholder="جستجوی نام یا نماد…" aria-label="جستجوی دارایی" value={search} onChange={e=>setSearch(e.target.value)}/></label></div><div className="dash-assets-toolbar"><label><Switch checked={prefs.hide_small_assets} onCheckedChange={v=>void savePref({hide_small_assets:v})} disabled={busy} aria-label="پنهان کردن دارایی خرد"/>پنهان‌کردن دارایی‌های کمتر از ۱۰ هزار تومان</label></div><div className="dash-table-scroll"><table><thead><tr><th>دارایی</th><th>موجودی کل</th><th>رزروشده</th><th>در دسترس</th><th>عملیات</th></tr></thead><tbody>{positions.map(p=>{
    const isCash=isCashPosition(p),project=catalog.projects.find(project=>project.id===p.project_id),supported=isCash||p.asset_symbol==='USDT'&&!p.project_id;
    const scale=isCash&&p.asset_symbol==='IRR'?BigInt(10):BigInt(1),amount=(v:string)=>number(unitsDecimal(decimalUnits(v)/scale),isCash?1:8);
    return <tr key={p.id}><td><span className="dash-asset-symbol">{isCash?<CreditCard size={19}/>:p.asset_symbol.slice(0,1)}</span><span><strong>{isCash?'تومان':localized(p.asset_name,locale)||p.asset_symbol}</strong><small>{isCash?'TMN':p.asset_symbol}</small></span></td><td>{amount(p.quantity)}</td><td>{amount(p.locked_quantity)}</td><td>{amount(unitsDecimal(decimalUnits(p.quantity)-decimalUnits(p.locked_quantity)))}</td><td><div className="wallet-asset-actions">{supported&&<Link href={isCash?'/wallet/deposit':'/wallet/deposit?tab=token'}>واریز</Link>}<WalletActionLink action="withdrawal" href={isCash?'/wallet/withdraw':`/wallet/withdraw?tab=token&asset=${encodeURIComponent(p.asset_symbol)}${p.project_id?'&project='+encodeURIComponent(p.project_id):''}`}>برداشت</WalletActionLink>{!isCash&&<WalletActionLink action="trading" href={project?`/projects/${project.slug}`:'/#market'}>معامله</WalletActionLink>}</div></td></tr>;
   })}</tbody></table></div>{!positions.length&&<div className="dash-empty"><Wallet size={30}/><h3>{search?'دارایی با این نام پیدا نشد':'دارایی‌ای با این فیلتر وجود ندارد'}</h3><p>پس از تأیید واریز یا دریافت توکن، موجودی در این بخش به‌روز می‌شود.</p></div>}</section>
  <section className="dash-card wallet-home-bank"><span className="wallet-home-symbol"><CreditCard size={25}/></span><div><h2>حساب‌های بانکی شما</h2><p>{dashboardNumber(data.banks.length,locale,0)} حساب ثبت‌شده · مدیریت کارت و شماره شبا</p></div><button className="dash-secondary" onClick={onAddBank}><Plus size={17}/>افزودن حساب</button><Link href="/account/banks" className="dash-link">مدیریت حساب‌ها<ArrowLeft size={16}/></Link></section>
  <div id="wallet-addresses" className="wallet-home-addresses"><WalletAddressManagement wallets={data.wallets}/></div>
  <FundingHistory compact/>
  <details className="dash-card wallet-demo-disclosure"><summary><span>موجودی آزمایشی <small>برای تست؛ غیرقابل برداشت</small></span><ChevronDown size={18}/></summary><DemoBalance/></details>
 </div>;
}
