'use client';
import {useEffect,useState} from 'react';
import Link from 'next/link';
import {toast} from 'sonner';
import {Copy,Users,Link2,Wallet,ArrowRight} from 'lucide-react';
import {WorkspaceShell} from '@/components/workspace-shell';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {api} from '@/components/providers';
type Customer={id:string;joinedAt:string;plan:{plan:string;status:string;source:string}};
type Payout={id:string;method:string;destination:string;amountCents:number;status:string;createdAt:string};
type CreatorInfo={userId:string;active:boolean;percent:25|35|45|50};
type Affiliate={code:string;summary:{clicks:number;startedCheckouts:number;paidConversions:number;earningsCents:number;pendingCents:number;availableCents:number;commissionPercent:number;payouts:Payout[]};customers:Customer[];payoutMethod:{method:string;destination:string}|null};
const money=(c:number)=>new Intl.NumberFormat('en-US',{style:'currency',currency:'USD'}).format(c/100);
export default function Affiliate(){const[data,setData]=useState<Affiliate|null>(null),[error,setError]=useState(''),[method,setMethod]=useState('PayPal'),[destination,setDestination]=useState(''),[amount,setAmount]=useState(''),[busy,setBusy]=useState(false),[creator,setCreator]=useState<CreatorInfo|null>(null),[creatorRequests,setCreatorRequests]=useState<{status:string}[]>([]),[leaders,setLeaders]=useState<Array<{label:string;isCreator:boolean;paidConversions:number;commissionCents:number}>>([]);
 async function reload(){try{const response=await api('/api/affiliate');setData(response);setError('');void api('/api/affiliate/leaderboard').then(x=>setLeaders(x.leaders||[])).catch(()=>{});void api('/api/creator').then(x=>{setCreator(x.creator||null);setCreatorRequests(x.requests||[])}).catch(()=>{});setMethod(response.payoutMethod?.method||'PayPal');setDestination(response.payoutMethod?.destination||'')}catch(e){setError((e as Error).message)}}
 useEffect(()=>{void reload()},[]);
 async function requestFifty(){try{await api('/api/creator',{method:'POST',body:'{}'});toast.success('50% rate request sent to the owner');await reload()}catch(e){toast.error((e as Error).message)}}
 async function copy(){const url=window.location.origin+'/signup?ref='+encodeURIComponent(data?.code||'');try{await navigator.clipboard.writeText(url);toast.success('Affiliate link copied')}catch{toast.error('Unable to copy. Select the link manually.')}}
 async function saveMethod(){setBusy(true);try{await api('/api/affiliate/payout',{method:'POST',body:JSON.stringify({operation:'method',method,destination})});toast.success('Payout destination saved');await reload()}catch(e){toast.error((e as Error).message)}finally{setBusy(false)}}
 async function requestPayout(){const cents=Math.round(Number(amount)*100);if(!window.confirm(`Request a manual payout of ${money(cents)}? This does not send money immediately.`))return;setBusy(true);try{await api('/api/affiliate/payout',{method:'POST',body:JSON.stringify({operation:'request',amountCents:cents})});toast.success('Payout requested for owner review');setAmount('');await reload()}catch(e){toast.error((e as Error).message)}finally{setBusy(false)}}
 return <WorkspaceShell title="Affiliate Dashboard" description="Track referral visits, customer signups, confirmed checkout activity, and commission records.">
 {error?<p className="glass-panel p-6 text-destructive">{error}</p>:!data?<p className="glass-panel p-6">Loading your affiliate dashboard…</p>:<>
 <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">{[['Link clicks',data.summary.clicks],['Signups',data.customers.length],['Started checkouts',data.summary.startedCheckouts],['Paid conversions',data.summary.paidConversions]].map(([label,val])=><div key={label} className="glass-panel p-5"><p className="text-xs text-muted-foreground">{label}</p><p className="text-3xl font-black mt-2">{val}</p></div>)}</div>
 <div className="grid md:grid-cols-3 gap-3 mt-3">{[['Total earnings',data.summary.earningsCents],['Pending payout requests',data.summary.pendingCents],['Available balance',data.summary.availableCents]].map(([label,cents])=><div className="glass-panel p-5" key={label}><p className="text-xs text-muted-foreground">{label}</p><p className="font-black text-3xl mt-2">{money(Number(cents))}</p></div>)}</div>
 {creator&&<section className="glass-panel p-6 mt-5"><h2 className="font-bold text-lg">Creator access</h2><p className="text-sm text-muted-foreground mt-2">Your Creator role includes all currently available LARP experiences. Your referral commission tier is {creator.percent}% on eligible future confirmed conversions.</p>{creator.percent<50&&<Button variant="outline" className="mt-3" disabled={creatorRequests.some(x=>x.status==='pending')} onClick={()=>void requestFifty()}>{creatorRequests.some(x=>x.status==='pending')?'50% request pending':'Request 50% rate'}</Button>}</section>}
 <section className="glass-panel p-6 mt-5"><h2 className="font-bold flex gap-2 items-center"><Link2 size={18} className="text-primary"/> Affiliate invite link</h2><p className="mt-2 text-xs text-muted-foreground">Commission rate: {data.summary.commissionPercent}% of eligible confirmed checkout totals. A 0% rate means commissions have not yet been enabled by the owner.</p><div className="mt-3 flex flex-col md:flex-row gap-2"><Input readOnly value={typeof window==='undefined'?'':window.location.origin+'/signup?ref='+encodeURIComponent(data.code||'')}/><Button onClick={()=>void copy()}><Copy size={15}/> Copy</Button></div><Link href="/referrals" className="text-xs text-primary flex gap-2 items-center mt-3">Referral invite page <ArrowRight size={13}/></Link></section>
 <section className="glass-panel p-6 mt-5"><h2 className="font-bold flex gap-2 items-center"><Users size={18} className="text-primary"/> Referred customers</h2><div className="overflow-x-auto mt-4"><table className="w-full text-left text-xs"><thead><tr className="border-b text-muted-foreground"><th className="py-3">Customer ID</th><th>Join date</th><th>Current plan</th><th>Subscription status</th></tr></thead><tbody>{data.customers.map(u=><tr className="border-b border-border/50" key={u.id}><td className="font-mono py-3 pr-3">{u.id}</td><td>{new Date(u.joinedAt).toLocaleDateString()}</td><td className="capitalize">{u.plan.plan}</td><td className="capitalize">{u.plan.status.replaceAll('_',' ')}</td></tr>)}</tbody></table>{!data.customers.length&&<p className="py-5 text-muted-foreground">Nobody has joined through your referral link yet.</p>}</div></section>
 <section className="glass-panel p-6 mt-5"><h2 className="font-bold text-lg">Affiliate & Creator Leaderboard</h2><p className="text-xs text-muted-foreground mt-2">Ranks are based on recorded confirmed paid conversions, not link clicks. Member names are only shown when they choose a public @handle.</p><div className="space-y-2 mt-4">{leaders.map((leader,i)=><div key={i} className="flex items-center justify-between gap-3 border border-border rounded-lg p-3"><span className="text-sm"><b>#{i+1}</b> {leader.label} {leader.isCreator&&<span className="text-primary text-xs font-bold">Creator</span>}</span><span className="text-xs text-muted-foreground">{leader.paidConversions} paid conversions</span></div>)}{!leaders.length&&<p className="text-sm text-muted-foreground">No confirmed referral conversions yet.</p>}</div></section>
 <div className="grid lg:grid-cols-2 gap-5 mt-5"><section className="glass-panel p-6"><h2 className="font-bold flex gap-2"><Wallet size={18} className="text-primary"/> Payout preferences</h2><p className="text-xs text-muted-foreground mt-2">Choose where the owner should send your earnings. PayPal, Venmo, Cash App, and Crypto are recorded as manual payout destinations; this site does not transfer money automatically.</p><div className="grid grid-cols-2 gap-3 mt-4"><label className="text-xs">Method<select value={method} onChange={e=>setMethod(e.target.value)} className="w-full mt-1 rounded-lg h-10 bg-background border px-2">{['PayPal','Venmo','Cash App','Crypto'].map(m=><option key={m}>{m}</option>)}</select></label><label className="text-xs">Destination<input type="text" value={destination} onChange={e=>setDestination(e.target.value)} placeholder="Payment handle or wallet" className="w-full h-10 mt-1 bg-background border border-border rounded-lg px-3"/></label></div><Button className="mt-3" disabled={busy} variant="outline" onClick={()=>void saveMethod()}>Save payout method</Button><div className="flex gap-2 mt-6"><Input type="number" step="0.01" min="1" aria-label="Payout amount in USD" placeholder="Amount in USD" value={amount} onChange={e=>setAmount(e.target.value)}/><Button disabled={busy||!data.payoutMethod||!amount||Number(amount)<=0||Math.round(Number(amount)*100)>data.summary.availableCents} onClick={()=>void requestPayout()}>Request payout</Button></div></section>
 <section className="glass-panel p-6"><h2 className="font-bold">Payout history</h2>{!data.summary.payouts.length?<p className="text-sm text-muted-foreground mt-5">No payouts have been requested.</p>:<div className="space-y-3 mt-4">{data.summary.payouts.slice().reverse().map(p=><div className="border border-border rounded-xl p-3" key={p.id}><div className="flex justify-between"><b className="text-sm">{money(p.amountCents)}</b><span className="text-xs capitalize">{p.status}</span></div><p className="text-xs text-muted-foreground mt-1">{p.method} · {new Date(p.createdAt).toLocaleDateString()}</p></div>)}</div>}</section></div>
 </>}
 </WorkspaceShell>;
}
