'use client';
import{useCallback,useEffect,useRef,useState}from'react';
import{RefreshCw,ShieldCheck}from'lucide-react';import Link from 'next/link';
import{useAccount}from'@/components/providers';
import{Button}from'@/components/ui/button';
type PlanKey='day1'|'day3'|'week'|'month'|'quarter'|'lifetime'|'free';
type Purchase={plan:PlanKey;active:boolean;expiresAt:number|null;updatedAt:string;stripeSubscription?:string;cancelAtPeriodEnd?:boolean};
const names:Record<PlanKey,string>={day1:'1-Day Pass',day3:'3-Day Pass',week:'Weekly',month:'Monthly',quarter:'Quarterly',lifetime:'Lifetime',free:'Free'};
export function CurrentPlan(){
 const{user,loading:userLoading}=useAccount();
 const[success,setSuccess]=useState(false);const[assigned,setAssigned]=useState<{plan:PlanKey;active:boolean;source:string;status:string;packageName?:string;expiresAt?:number|null}|null>(null),[purchases,setPurchases]=useState<Purchase[]>([]),[loading,setLoading]=useState(true),[syncing,setSyncing]=useState(false),[error,setError]=useState(''),[syncError,setSyncError]=useState(''),[lastSync,setLastSync]=useState<number|null>(null),[cancelConfirm,setCancelConfirm]=useState(false),[cancelBusy,setCancelBusy]=useState(false),[cancelError,setCancelError]=useState('');
 const confirmedSessions=useRef(new Set<string>());
 const refresh=useCallback(async()=>{
  if(!user){setPurchases([]);setAssigned(null);setLoading(false);return}
  try{const response=await fetch('/api/billing/status',{cache:'no-store',credentials:'same-origin'});const data=await response.json();if(!response.ok)throw Error();setPurchases(Array.isArray(data.purchases)?data.purchases:[]);setAssigned(data.currentPlan||null);setError('');setLastSync(Date.now())}
  catch{setError('Could not load your plan. Please refresh in a moment.')}
  finally{setLoading(false)}
 },[user]);
 useEffect(()=>{
  if(userLoading)return;
  let cancelled=false;
  async function loadPlan(){
   const params=new URLSearchParams(window.location.search),sessionId=params.get('session_id');
   if(user&&params.get('checkout')==='complete'&&sessionId&&!confirmedSessions.current.has(sessionId)){
    confirmedSessions.current.add(sessionId);setSyncing(true);setSyncError('');
    let confirmed=false;for(let attempt=0;attempt<3&&!confirmed;attempt++){try{const response=await fetch('/api/billing/confirm',{method:'POST',headers:{'Content-Type':'application/json'},credentials:'same-origin',body:JSON.stringify({sessionId})});if(!response.ok)throw Error();confirmed=true;if(!cancelled)setSuccess(true);window.dispatchEvent(new Event('billing:updated'))}catch{if(attempt<2)await new Promise(resolve=>window.setTimeout(resolve,1000*(attempt+1)))}}
    if(!confirmed&&!cancelled)setSyncError('We couldn’t finish setting up your plan yet. Please refresh in a moment. If it still doesn’t appear, contact Support.');
    if(!cancelled)setSyncing(false);
   }
   if(!cancelled)await refresh();
  }
  void loadPlan();const sync=()=>void refresh(),timer=window.setInterval(sync,10000);window.addEventListener('billing:updated',sync);return()=>{cancelled=true;window.clearInterval(timer);window.removeEventListener('billing:updated',sync)}
 },[refresh,user,userLoading]);
 const current=purchases.filter(p=>p.active&&(p.expiresAt===null||p.expiresAt>Date.now())).sort((a,b)=>Date.parse(b.updatedAt)-Date.parse(a.updatedAt))[0];
 async function cancelPlan(){if(!current?.stripeSubscription)return;setCancelBusy(true);setCancelError('');try{const response=await fetch('/api/billing/cancel',{method:'POST',headers:{'Content-Type':'application/json'},credentials:'same-origin',body:'{}'});const data=await response.json();if(!response.ok)throw Error(data.error||'Could not cancel your plan');setPurchases(items=>items.map(p=>p.stripeSubscription===current.stripeSubscription?{...p,cancelAtPeriodEnd:true}:p));setCancelConfirm(false);window.dispatchEvent(new Event('billing:updated'))}catch(e){setCancelError((e as Error).message||'Could not cancel your plan. Please try again.')}finally{setCancelBusy(false)}}
 const endDate=current?.expiresAt?new Date(current.expiresAt).toLocaleDateString():'';
 return <section className="glass-panel p-5 mt-8" aria-live="polite">{success&&<div className="rounded-lg border border-emerald-500/40 bg-emerald-500/10 p-4 mb-4"><p className="font-bold">Payment verified. Your plan is now connected to your account.</p><p className="text-xs text-muted-foreground mt-1">You do not need to buy again. Continue to your saved LARPs.</p><Button asChild variant="gradient" size="sm" className="mt-3"><Link href="/my-larps">Go to My LARPs</Link></Button></div>}
  <div className="flex flex-wrap items-center justify-between gap-3"><div className="flex items-center gap-3"><ShieldCheck className="text-primary shrink-0"/><div><h2 className="font-extrabold">Your current plan</h2>{syncing?<p className="text-sm text-muted-foreground mt-1">Finishing setup for your plan…</p>:userLoading||loading?<p className="text-sm text-muted-foreground mt-1">Checking your plan…</p>:!user?<p className="text-sm text-muted-foreground mt-1">Sign in to see your plan.</p>:assigned?.source==='creator'?<p className="text-sm mt-1"><b>Creator access</b> · Available LARPs included</p>:assigned?.source==='trial'?<p className="text-sm mt-1"><b>Free trial</b> · Ends {assigned.expiresAt?new Date(assigned.expiresAt).toLocaleDateString():'soon'}</p>:assigned?.source==='owner'?<p className="text-sm mt-1"><span className="font-bold">{names[assigned.plan]||assigned.plan}</span> · Owner-assigned {assigned.plan==='free'?'free access':'access'} <span className="text-xs text-muted-foreground">(separate Stripe billing may still renew)</span>{assigned.expiresAt?<span className="text-xs text-amber-400"> · Access ends {new Date(assigned.expiresAt).toLocaleDateString()}</span>:null}</p>:current?.cancelAtPeriodEnd?<p className="text-sm mt-1"><span className="font-bold">{assigned?.packageName||names[current.plan]}</span> · Ends {endDate||'at the end of this billing period'}</p>:current?<p className="text-sm mt-1"><span className="font-bold">{assigned?.packageName||names[current.plan]}</span> · Active{current.plan==='lifetime'?' · Lifetime access':endDate?` through ${endDate}`:''}</p>:<p className="text-sm text-muted-foreground mt-1">No active plan yet. Your plan will appear here after checkout.</p>}</div></div><Button type="button" size="sm" variant="outline" onClick={()=>void refresh()} disabled={!user||loading||syncing}><RefreshCw size={15} className={loading||syncing?'animate-spin':''}/> Refresh plan</Button></div>
  {assigned?.active&&<div className="mt-4"><Button asChild variant="gradient" size="sm"><Link href="/my-larps">Open My LARPs — no checkout needed</Link></Button></div>}
  {current?.stripeSubscription&&!current.cancelAtPeriodEnd&&<div className="border-t border-border mt-4 pt-4">{cancelConfirm?<div className="flex flex-wrap items-center justify-between gap-3"><p className="text-sm text-muted-foreground">Your plan stays active through {endDate||'the current billing period'} and won’t renew after that.</p><div className="flex gap-2"><Button type="button" size="sm" variant="outline" onClick={()=>setCancelConfirm(false)} disabled={cancelBusy}>Keep my plan</Button><Button type="button" size="sm" variant="outline" className="text-red-500 border-red-500/40 hover:bg-red-500/10" onClick={()=>void cancelPlan()} disabled={cancelBusy}>{cancelBusy?'Scheduling…':'Yes, cancel renewal'}</Button></div></div>:<Button type="button" size="sm" variant="outline" onClick={()=>{setCancelError('');setCancelConfirm(true)}}>Cancel plan</Button>}</div>}
  {current?.cancelAtPeriodEnd&&<p className="text-sm text-muted-foreground border-t border-border mt-4 pt-4">Your plan won’t renew. You’ll keep access through {endDate||'the end of this billing period'}.</p>}
  {error&&<p role="alert" className="text-sm text-destructive mt-3">{error}</p>}{syncError&&<p role="alert" className="text-sm text-destructive mt-3">{syncError}</p>}{cancelError&&<p role="alert" className="text-sm text-destructive mt-3">{cancelError}</p>}{user&&lastSync&&!loading&&!error&&<p className="text-xs text-muted-foreground mt-3">Last updated {new Date(lastSync).toLocaleTimeString()}.</p>}
 </section>
}
