'use client';

import {useEffect,useLayoutEffect,useRef,useState} from 'react';
import {ArrowUpRight,ShieldCheck} from 'lucide-react';
import {coinWithdrawalInput} from '@/lib/coin-withdrawal';
import {fundingReviewView} from '@/lib/funding-review';
import {dashboardNumber,decimalUnits,unitsDecimal} from '@/lib/dashboard';
import {walletActionAccess} from '@/lib/wallet-action-access';
import {type FundingNetwork} from '@/lib/wallet-funding';
import {useSite} from './site-shell';
import {useVerificationClock} from './use-verification-clock';
import {LocalizedNumberInput} from './localized-number-input';
import Link from './account-link';

type Draft={request_id:string;network:FundingNetwork;address:string;amount:string};

/** A withdrawal request is distinct from a broadcast/settlement. */
export function CoinWithdrawalRequest(){const {user}=useSite();return <CoinWithdrawalBody key={user?.id||'guest'}/>}
function CoinWithdrawalBody(){
 const {user,customer,locale}=useSite();
 const [amount,setAmount]=useState(''),[network,setNetwork]=useState<FundingNetwork>('ethereum'),[address,setAddress]=useState('');
 const [busy,setBusy]=useState(false),[pending,setPending]=useState(false),[error,setError]=useState(''),[notice,setNotice]=useState('');
 const owner=user?.id,ownerRef=useRef(owner),mounted=useRef(true),lock=useRef(false),draft=useRef<Draft|null>(null),uncertain=useRef(false),storageKey='planck:coin-withdrawal:'+owner;
 useLayoutEffect(()=>{ownerRef.current=owner},[owner]);
 useEffect(()=>{
  mounted.current=true;let disposed=false;
  queueMicrotask(()=>{if(disposed)return;try{const saved=JSON.parse(sessionStorage.getItem(storageKey)||'null');if(saved){coinWithdrawalInput(saved);draft.current=saved;uncertain.current=true;setAmount(saved.amount);setNetwork(saved.network);setAddress(saved.address);setPending(true)}}catch{/* Ignore malformed drafts. */}});
  return()=>{disposed=true;mounted.current=false};
 },[storageKey]);
 const now=useVerificationClock(customer.data?.account.temporary_expires_at,customer.reload);
 const access=walletActionAccess(user?.access,customer.data?.account,'withdrawal',now);
 const real=customer.data?.positions.filter(p=>p.asset_symbol==='USDT'&&p.project_id===null)||[];
 const available=real.reduce((sum,p)=>sum+decimalUnits(p.quantity)-decimalUnits(p.locked_quantity),BigInt(0));
 const displayAmount=customer.data?.preferences?.hide_balances?'••••••':dashboardNumber(unitsDecimal(available),locale,6);
 let valid=false;try{coinWithdrawalInput({request_id:'11111111-1111-4111-8111-111111111111',network,address,amount});valid=true}catch{/* Validate before submission. */}
 const alive=()=>mounted.current&&ownerRef.current===owner;
 async function submit(){
  if(!owner||!alive()||lock.current||!access.allowed||(!draft.current&&!valid))return;
  if(!draft.current){draft.current={request_id:crypto.randomUUID(),network,address:address.trim(),amount};uncertain.current=false;setPending(true);try{sessionStorage.setItem(storageKey,JSON.stringify(draft.current))}catch{}}
  lock.current=true;setBusy(true);setError('');setNotice('');
  try{
   const response=await fetch('/api/funding/coin-withdrawals',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(draft.current),signal:AbortSignal.timeout(30000)});
   const body=await response.json() as {error?:string};
   if(!alive())return;
   if(!response.ok){
    if([400,422].includes(response.status)&&!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(review.kind!=='withdrawal'||review.currency!=='USDT'||review.direction!=='withdrawal')throw new Error('پاسخ درخواست معتبر نیست؛ همان درخواست را دوباره بررسی کنید.');
   draft.current=null;uncertain.current=false;setPending(false);try{sessionStorage.removeItem(storageKey)}catch{}
   setNotice(review.execution_status==='released'?'این درخواست رد شده و مبلغ رزروشده آزاد شده است.':review.execution_status==='awaiting_payout'?'مدیر درخواست را تأیید کرده است؛ انتقال روی شبکه هنوز انجام نشده است.':'درخواست برداشت تتر ثبت شد و مبلغ رزرو شد. نتیجه بررسی مدیر در تاریخچه و اعلان‌ها نمایش داده می‌شود؛ هنوز انتقالی روی شبکه انجام نشده است.');
   setAmount('');void customer.reload();window.dispatchEvent(new Event('planck:funding-review-updated'));
  }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"><ArrowUpRight size={23}/></span><div><h2>درخواست برداشت کوین</h2><p>برداشت تتر به آدرس والت مقصد · بررسی دستی مدیر</p></div></header>
  {!access.allowed?<div className="funding-error" role="status"><ShieldCheck size={18}/><p>{access.message}</p>{access.identityRequired&&<Link href="/account/profile" className="dash-secondary">تکمیل احراز هویت</Link>}</div>:<>
   <p className="funding-note">موجودی واقعی در دسترس: <bdi>{displayAmount} USDT</bdi>. موجودی آزمایشی قابل برداشت نیست.</p>
   <form onSubmit={e=>{e.preventDefault();void submit()}} aria-busy={busy}>
    <label className="funding-field"><span>دارایی</span><select aria-label="دارایی برداشت" disabled><option>تتر · USDT</option></select></label>
    <label className="funding-field"><span>شبکه انتقال</span><select value={network} onChange={e=>setNetwork(e.target.value as FundingNetwork)} disabled={busy||pending}><option value="ethereum">Ethereum · ERC-20</option><option value="tron">Tron · TRC-20</option></select></label>
    <label className="funding-field"><span>آدرس والت مقصد</span><input dir="ltr" autoComplete="off" spellCheck={false} maxLength={64} placeholder={network==='ethereum'?'0x…':'T…'} value={address} onChange={e=>setAddress(e.target.value)} disabled={busy||pending} required/></label>
    <label className="funding-field"><span>مقدار برداشت (USDT)</span><LocalizedNumberInput value={amount} onValueChange={setAmount} locale={locale} disabled={busy||pending} required placeholder="۰"/></label>
    <p className="funding-note">شبکه مقصد باید با شبکه انتخاب‌شده یکسان باشد. این مرحله فقط درخواست و رزرو مبلغ را ثبت می‌کند؛ انتقال و کارمزد نهایی پس از بررسی مدیریت مشخص می‌شود.</p>
    <button className="funding-primary" disabled={busy||!owner||(!pending&&!valid)}>{busy?'در حال ثبت…':pending?'بررسی دوباره همان درخواست':'ثبت درخواست برداشت تتر'}</button>
   </form>
  </>}
  {error&&<p className="funding-error" role="alert">{error}</p>}{notice&&<output className="funding-pending-note">{notice} <Link href="/wallet/transactions">پیگیری درخواست</Link></output>}
 </section>;
}
