'use client';

import {useCallback,useEffect,useLayoutEffect,useRef,useState} from 'react';
import {ArrowDownLeft,ArrowUpRight,CheckCircle2,ChevronDown,Clock3,FileSearch,RefreshCw,ShieldCheck,TriangleAlert,Wallet} from 'lucide-react';
import {fundingHistoryView,fundingReviewView,fundingKind,fundingStatus,fundingExecution,withdrawalInput,type FundingReview} from '@/lib/funding-review';
import {dashboardNumber,decimalUnits,unitsDecimal} from '@/lib/dashboard';
import {cashWallet} from '@/lib/cash-wallet';
import {rialToToman} from '@/lib/trade';
import {accessRestriction} from '@/lib/account-access';
import {useSite} from './site-shell';
import {LocalizedNumberInput} from './localized-number-input';
import Link from './account-link';

const reviewEvent='planck:funding-review-updated';
const money=(row:FundingReview)=>row.currency==='IRR'?unitsDecimal(decimalUnits(row.amount)/BigInt(10)):row.amount;
function Status({row}:{row:FundingReview}){return <span className={'funding-status is-'+row.status}>{row.status==='pending'?<Clock3 size={13}/>:row.status==='approved'?<CheckCircle2 size={13}/>:<TriangleAlert size={13}/>} {fundingStatus[row.status]}</span>}
function ReviewItem({row}:{row:FundingReview}){
 const {locale,customer}=useSite(),hidden=customer.data?.preferences?.hide_balances;
 const date=(v:string)=>new Intl.DateTimeFormat(locale,{dateStyle:'medium',timeStyle:'short'}).format(new Date(v));
 return <details className="funding-review-row"><summary>
  <span className="funding-review-direction">{row.direction==='deposit'?<ArrowDownLeft size={21}/>:<ArrowUpRight size={21}/>}</span>
  <span className="funding-review-title"><strong>{row.kind==='withdrawal'&&row.currency==='USDT'?'برداشت تتر':fundingKind[row.kind]}{row.test_mode&&row.kind!=='demo'?' · آزمایشی':''}</strong><time dateTime={row.created_at}>{date(row.created_at)}</time></span>
  <span className="funding-review-amount">{hidden?'••••••':dashboardNumber(money(row),locale,6)} <small>{row.currency==='IRR'?'تومان':'USDT'}{row.test_mode?' آزمایشی':''}</small></span>
  <Status row={row}/><span className="funding-review-detail-link">جزئیات <ChevronDown size={14}/></span>
 </summary><div className="funding-review-details">
  <p className="funding-review-execution"><ShieldCheck size={17}/>{fundingExecution[row.execution_status]}</p>
  {row.test_mode&&<p className="funding-note">موجودی آزمایشی ارزش نقدی ندارد و قابل برداشت نیست.</p>}
  <div className="funding-review-checks">{row.checks.map(check=><div key={check.key} className={'funding-check is-'+check.status}>{check.status==='passed'?<CheckCircle2 size={18}/>:check.status==='failed'?<TriangleAlert size={18}/>:<Clock3 size={18}/>}<span><strong>{check.label}</strong><small>{check.detail}</small></span></div>)}</div>
  {row.review_note&&<div className="funding-review-message"><strong>پیام مدیریت</strong><p>{row.review_note}</p></div>}
  <footer><span>نحوه بررسی: {row.manual_required?'تأیید دستی مدیر':row.automatic_enabled?'تأیید خودکار پس از تکمیل بررسی‌ها':'در انتظار تصمیم مدیر'}</span><span>آخرین تغییر: <time dateTime={row.updated_at}>{date(row.updated_at)}</time></span><span>شناسه درخواست: <bdi>{row.id}</bdi></span></footer>
 </div></details>;
}
export function FundingHistory({compact=false}:{compact?:boolean}){const {user}=useSite();return <FundingHistoryBody key={user?.id||'guest'} compact={compact}/>}
function FundingHistoryBody({compact}:{compact:boolean}){
 const {user,customer}=useSite(),owner=user?.id,reload=customer.reload,ownerRef=useRef(owner),mounted=useRef(true),controller=useRef<AbortController|null>(null),seq=useRef(0),fingerprint=useRef<string|null>(null);
 const [rows,setRows]=useState<FundingReview[]|null>(null),[loading,setLoading]=useState(true),[error,setError]=useState(''),[filter,setFilter]=useState('all');
 useLayoutEffect(()=>{ownerRef.current=owner},[owner]);
 const load=useCallback(async(background=false)=>{
  if(!owner)return;if(background&&controller.current)return;controller.current?.abort();const abort=new AbortController();controller.current=abort;const n=++seq.current;
  if(!background)setLoading(true);
  try{const response=await fetch('/api/funding/reviews',{cache:'no-store',signal:abort.signal}),body=await response.json() as {error?:string};if(!response.ok)throw new Error(body.error||'تاریخچه واریز و برداشت دریافت نشد.');const result=fundingHistoryView(body);
   if(!mounted.current||ownerRef.current!==owner||n!==seq.current)return;
   const key=result.items.map(r=>r.id+':'+r.version+':'+r.status+':'+r.execution_status).join('|');
   if(fingerprint.current!==null&&fingerprint.current!==key){void reload();window.dispatchEvent(new CustomEvent('planck:demo-wallet-updated',{detail:{userId:owner,at:Date.now()}}));}
   fingerprint.current=key;setRows(result.items);setError('');
  }catch(e){if(!abort.signal.aborted&&mounted.current&&ownerRef.current===owner&&n===seq.current)setError(e instanceof Error?e.message:'دریافت اطلاعات انجام نشد.');}
  finally{if(mounted.current&&n===seq.current){controller.current=null;setLoading(false)}}
 },[owner,reload]);
 useEffect(()=>{mounted.current=true;let disposed=false;queueMicrotask(()=>{if(!disposed)void load()});const refresh=()=>{if(document.visibilityState==='visible')void load(true)};const timer=setInterval(refresh,15000);window.addEventListener('focus',refresh);window.addEventListener(reviewEvent,refresh);document.addEventListener('visibilitychange',refresh);return()=>{disposed=true;mounted.current=false;seq.current++;controller.current?.abort();clearInterval(timer);window.removeEventListener('focus',refresh);window.removeEventListener(reviewEvent,refresh);document.removeEventListener('visibilitychange',refresh)}},[load]);
 if(!owner)return null;
 const shown=(rows||[]).filter(r=>filter==='all'||r.status===filter).slice(0,compact?5:50);
 return <section className="wallet-funding funding-review-list" aria-labelledby={compact?'funding-recent-title':'funding-history-title'} aria-busy={loading}>
  <header className="funding-heading"><span className="funding-icon"><FileSearch size={22}/></span><div><h2 id={compact?'funding-recent-title':'funding-history-title'}>{compact?'آخرین وضعیت واریز و برداشت':'پیگیری واریزها و برداشت‌ها'}</h2><p>نتیجهٔ بررسی‌ها و پیام مدیریت برای هر درخواست</p></div><button className="funding-icon-button" aria-label="تازه‌سازی وضعیت واریز و برداشت" disabled={loading} onClick={()=>void load()}><RefreshCw size={17} className={loading?'funding-spin':''}/></button></header>
  {!compact&&<div className="funding-review-filters" role="group" aria-label="فیلتر وضعیت">{[['all','همه'],...Object.entries(fundingStatus)].map(([value,label])=><button key={value} type="button" aria-pressed={filter===value} onClick={()=>setFilter(value)}>{label}</button>)}</div>}
  {error&&<p className="funding-error" role="alert">{error}</p>}
  {rows===null&&loading?<div className="funding-history-loading" role="status"><span/>در حال دریافت وضعیت درخواست‌ها…</div>:shown.length?shown.map(row=><ReviewItem key={row.id} row={row}/>):!error&&<p className="funding-note">درخواستی با این وضعیت ثبت نشده است.</p>}
  {compact&&<Link className="funding-history-all" href="/wallet/transactions">مشاهده همه درخواست‌ها و جزئیات</Link>}
 </section>;
}

export function WithdrawalRequest(){const {user}=useSite();return <WithdrawalBody key={user?.id||'guest'}/>}
function WithdrawalBody(){
 const {user,customer,locale}=useSite(),[amount,setAmount]=useState(''),[bank,setBank]=useState(''),[busy,setBusy]=useState(false),[error,setError]=useState(''),[notice,setNotice]=useState(''),[pending,setPending]=useState(false);
 const owner=user?.id,ownerRef=useRef(owner),mounted=useRef(true),lock=useRef(false),draft=useRef<{request_id:string;amount_toman:string;bank_id:string}|null>(null),uncertain=useRef(false),storageKey='planck:withdrawal:'+owner;
 useLayoutEffect(()=>{ownerRef.current=owner},[owner]);
 const alive=()=>mounted.current&&ownerRef.current===owner;
 useEffect(()=>{mounted.current=true;let disposed=false;queueMicrotask(()=>{if(disposed)return;try{const value=JSON.parse(sessionStorage.getItem(storageKey)||'null');if(value){withdrawalInput(value);draft.current=value;uncertain.current=true;setAmount(value.amount_toman);setBank(value.bank_id);setPending(true)}}catch{/* Ignore invalid drafts. */}});return()=>{disposed=true;mounted.current=false}},[storageKey]);
 const balance=customer.data?cashWallet(customer.data.positions):null,banks=customer.data?.banks.filter(b=>!!b.ownership_checked_at&&b.status==='verified')||[],restriction=accessRestriction(user?.access,'withdrawal');
 let valid=false;try{withdrawalInput({request_id:'11111111-1111-4111-8111-111111111111',amount_toman:amount,bank_id:bank});valid=true}catch{/* Disabled until valid. */}
 async function submit(){
  if(!owner||!alive()||lock.current||(!draft.current&&(!valid||restriction)))return;
  let value=draft.current;
  if(!value){value={request_id:crypto.randomUUID(),amount_toman:amount,bank_id:bank};draft.current=value;uncertain.current=false;setPending(true);try{sessionStorage.setItem(storageKey,JSON.stringify(value))}catch{}}
  lock.current=true;setBusy(true);setError('');setNotice('');
  try{const r=await fetch('/api/funding/withdrawals',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(value),signal:AbortSignal.timeout(30000)}),body=await r.json() as {error?:string};
   if(!r.ok){if((r.status===400||r.status===422)&&!uncertain.current){draft.current=null;setPending(false);try{sessionStorage.removeItem(storageKey)}catch{}}else uncertain.current=true;throw new Error(body.error||'ثبت درخواست برداشت انجام نشد.');}
   const review=fundingReviewView(body);if(!alive())return;
   if(review.kind!=='withdrawal')throw new Error('پاسخ درخواست معتبر نیست.');
   draft.current=null;uncertain.current=false;setPending(false);try{sessionStorage.removeItem(storageKey)}catch{}
   setNotice('درخواست برداشت ثبت شد. مبلغ تا تعیین تکلیف رزرو می‌ماند؛ تأیید مدیر به معنی انجام انتقال بانکی نیست.');void customer.reload();window.dispatchEvent(new Event(reviewEvent));
  }catch(e){if(alive()){uncertain.current=!!draft.current;setError(e instanceof Error?e.message:'ارتباط کامل نشد؛ همان درخواست را دوباره بررسی کنید.')}}finally{if(alive()){lock.current=false;setBusy(false)}}
 }
 return <><section className="wallet-funding funding-withdrawal"><header className="funding-heading"><span className="funding-icon"><Wallet size={23}/></span><div><h2>درخواست برداشت تومان</h2><p>ثبت درخواست برای بررسی مدیر و پیگیری انتقال</p></div></header>
  {restriction&&<p className="funding-error">{restriction}</p>}
  <p className="funding-note">موجودی در دسترس: {customer.data?.preferences?.hide_balances?'••••••':dashboardNumber(balance?rialToToman(balance.availableRial):null,locale,1)} تومان. موجودی آزمایشی قابل برداشت نیست.</p>
  <form onSubmit={e=>{e.preventDefault();void submit()}} aria-busy={busy}><label className="funding-field"><span>مبلغ برداشت (تومان)</span><LocalizedNumberInput value={amount} onValueChange={setAmount} locale={locale} disabled={busy||pending||!!restriction} placeholder="۰"/></label><label className="funding-field"><span>حساب بانکی تأییدشده</span><select value={bank} onChange={e=>setBank(e.target.value)} disabled={busy||pending||!!restriction}><option value="">انتخاب حساب</option>{banks.map(b=><option key={b.id} value={b.id}>{b.bank_name} · {b.iban}</option>)}</select></label>
  {!banks.length&&<p className="funding-note">برای ثبت برداشت، یک حساب بانکی تأییدشده لازم است. <Link href="/account/banks">مدیریت حساب‌های بانکی</Link></p>}
  <p className="funding-note">در این مرحله فقط درخواست و رزرو مبلغ ثبت می‌شود. پس از تأیید مدیر، وضعیت تا انجام و تأیید انتقال بانکی «در انتظار پرداخت» خواهد بود.</p>
  <button className="funding-primary" disabled={busy||!owner||(!pending&&(!valid||!!restriction))}>{busy?'در حال ثبت…':pending?'بررسی دوباره همان درخواست':'ثبت درخواست برداشت'}</button></form>
  {error&&<p className="funding-error" role="alert">{error}</p>}{notice&&<output className="funding-pending-note">{notice}</output>}
 </section><FundingHistory/></>;
}
