'use client';
import {useCallback,useEffect,useState} from 'react';
import Link from 'next/link';
import {useRouter,useSearchParams} from 'next/navigation';
import {toast} from 'sonner';
import {useAccount} from '@/components/providers';
import {Button} from '@/components/ui/button';
import type {PlanKey,PurchasePlanKey} from '@/lib/billing-store';

type PurchaseSummary={plan:PurchasePlanKey;packageId?:string;active:boolean;expiresAt:number|null;updatedAt:string;stripeSubscription?:string;cancelAtPeriodEnd?:boolean};
type PlanSummary={plan:string;active:boolean;source?:string;status?:string};
const passPlans:PlanKey[]=['day1','day3'];
const names:Record<PlanKey,string>={day1:'1-Day Pass',day3:'3-Day Pass',week:'Weekly',month:'Monthly',quarter:'Quarterly'};

/** Never send an already-entitled account through another checkout without an explicit plan-change choice. */
export function CheckoutButton({plan,enabled,packageId,packageName}:{plan:PlanKey;enabled:boolean;packageId?:string;packageName?:string}){
 const {user,loading:accountLoading}=useAccount(),router=useRouter(),params=useSearchParams();
 const [busy,setBusy]=useState(false),[loading,setLoading]=useState(true),[verified,setVerified]=useState(false),[current,setCurrent]=useState<PurchaseSummary|null>(null);
 const [entitled,setEntitled]=useState(false),[activeAccount,setActiveAccount]=useState(false),[assigned,setAssigned]=useState<PlanSummary|null>(null),[switching,setSwitching]=useState(false);
 const target=packageName||names[plan];
 const promo=params.get('promo')||'';
 const returnTo='/pricing'+(promo?'?promo='+encodeURIComponent(promo):'');
 const authQuery='?next='+encodeURIComponent(returnTo+'#'+encodeURIComponent(packageId||plan));
 const refresh=useCallback(async()=>{
  if(!user){setCurrent(null);setEntitled(false);setActiveAccount(false);setAssigned(null);setVerified(false);setLoading(false);return;}
  setLoading(true);
  try{
   const r=await fetch('/api/billing/status',{cache:'no-store',credentials:'same-origin'});
   if(!r.ok)throw Error('Plan status unavailable');
   const data=await r.json();
   const active=(Array.isArray(data.purchases)?data.purchases:[] as PurchaseSummary[])
    .filter((item:PurchaseSummary)=>item.active&&(item.expiresAt===null||typeof item.expiresAt==='number'&&item.expiresAt>Date.now()))
    .sort((a:PurchaseSummary,b:PurchaseSummary)=>Date.parse(b.updatedAt)-Date.parse(a.updatedAt));
   setCurrent(active.find((p:PurchaseSummary)=>Boolean(p.stripeSubscription))||active[0]||null);
   setAssigned(data.currentPlan||null);
   setEntitled(Boolean(data.cashAppAccess));setActiveAccount(Boolean(data.currentPlan?.active));setVerified(true);
  }catch{setCurrent(null);setEntitled(false);setActiveAccount(false);setAssigned(null);setVerified(false);}
  finally{setLoading(false)}
 },[user]);
 useEffect(()=>{void refresh();const sync=()=>void refresh();window.addEventListener('billing:updated',sync);return()=>window.removeEventListener('billing:updated',sync)},[refresh]);
 const samePlan=Boolean(current&&(packageId?current.packageId===packageId:current.plan===plan));
 const eligibleToSwitch=Boolean(activeAccount&&!samePlan&&current?.stripeSubscription&&!current.cancelAtPeriodEnd&&assigned?.source!=='owner'&&!passPlans.includes(plan));
 async function buy(){
  if(!user){router.push('/signup'+authQuery);return;}
  if(!verified){toast.error('Could not check your current plan. Refresh before purchasing.');return;}
  if(activeAccount&&!switching){router.push('/my-larps');return;}
  setBusy(true);
  try{
   const r=await fetch('/api/billing/checkout',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify({plan,productSlug:'cash-app',packageId,promoCode:promo,...(switching&&current?.stripeSubscription?{replaceSubscriptionId:current.stripeSubscription}:{})})});
   const data=await r.json();
   if(!r.ok)throw Error(data.error||'Checkout is unavailable.');
   if(typeof data.url!=='string')throw Error('Secure checkout was not returned.');
   const url=new URL(data.url);
   if(url.protocol!=='https:'||url.hostname!=='checkout.stripe.com'&&!url.hostname.endsWith('.checkout.stripe.com'))throw Error('Secure checkout URL is invalid.');
   window.location.assign(url.href);
  }catch(e){toast.error((e as Error).message)}finally{setBusy(false)}
 }
 if(accountLoading)return <Button className="w-full mt-auto" variant="outline" disabled>Checking your account…</Button>;
 if(!user)return <div className="mt-auto pt-6 space-y-2"><Button variant="gradient" className="w-full" onClick={()=>router.push('/signup'+authQuery)} disabled={!enabled}>Create account to buy</Button><Link className="block text-center text-xs underline text-primary py-2" href={'/login'+authQuery}>Already registered? Sign in</Link></div>;
 if(loading)return <Button className="w-full mt-auto" variant="outline" disabled>Checking your access…</Button>;
 if(!verified)return <div className="mt-auto pt-6 space-y-2 text-center"><p className="text-xs text-amber-500">We couldn't verify your current subscription. No payment was started.</p><Button className="w-full" variant="outline" onClick={()=>void refresh()}>Retry account check</Button></div>;
 if(activeAccount&&!switching)return <div className="mt-auto pt-6 space-y-2"><Button className="w-full" variant="gradient" onClick={()=>router.push('/my-larps')}>{entitled?'Open My LARPs — already paid':'View My LARPs & existing plan'}</Button>{eligibleToSwitch&&<button type="button" className="w-full text-xs underline text-muted-foreground py-2" onClick={()=>setSwitching(true)}>Change subscription to {target}</button>}<p className="text-xs text-center text-muted-foreground">{entitled?'You have active access. No second purchase is required.':'Your account has a plan, but it may not include Cash App. Change packages explicitly or contact support.'}</p></div>;
 if(activeAccount&&switching)return <div className="mt-auto pt-6 space-y-2"><p className="text-xs text-amber-500">Changing packages starts a new subscription. Your previous subscription is cancelled after the new payment is confirmed.</p><Button variant="gradient" className="w-full" disabled={busy||!enabled} onClick={()=>void buy()}>{busy?'Opening secure checkout…':`Confirm change to ${target}`}</Button><Button variant="outline" className="w-full" onClick={()=>setSwitching(false)}>Keep my current plan</Button></div>;
 return <div className="mt-auto pt-6"><Button variant="gradient" className="w-full" disabled={busy||!enabled} onClick={()=>void buy()}>{!enabled?'Unavailable right now':busy?'Opening secure checkout…':`Continue to checkout · ${target}`}</Button></div>;
}
