'use client';
import React,{useEffect,useState} from 'react';
import Link from 'next/link';
import {useSearchParams} from 'next/navigation';
import {ArrowLeft,ArrowRight,Eye,EyeOff,KeyRound,Mail,ShieldCheck} from 'lucide-react';
import {Logo,ThemeToggle} from '@/components/common';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {Label} from '@/components/ui/label';

const post=async(url:string,data:Record<string,string>)=>{
 const response=await fetch(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data),credentials:'same-origin',cache:'no-store'});
 const body=await response.json().catch(()=>({}));
 if(!response.ok)throw Error(body.error||'Unable to complete this request.');
 return body as {message?:string};
};
export function PasswordRecoveryForm({mode}:{mode:'forgot'|'reset'}){
 const search=useSearchParams();
 const [email,setEmail]=useState(''),[token,setToken]=useState(''),[password,setPassword]=useState(''),[confirm,setConfirm]=useState(''),[show,setShow]=useState(false),[busy,setBusy]=useState(false),[done,setDone]=useState(false),[message,setMessage]=useState(''),[error,setError]=useState('');
 useEffect(()=>{
   if(mode!=='reset')return;
   const found=search.get('token')||'';
   if(found)setToken(found);
   // Keep the single-use reset credential out of the browser's visible URL after load.
   if(found&&typeof window!=='undefined')window.history.replaceState(window.history.state,'',window.location.pathname);
 },[mode,search]);
 const resetting=mode==='reset';
 async function submit(event:React.FormEvent<HTMLFormElement>){
   event.preventDefault();setError('');setMessage('');
   if(resetting&&password!==confirm){setError('The two passwords do not match.');return}
   if(resetting&&!token){setError('This link is missing a reset token. Request a new link.');return}
   setBusy(true);
   try{
     const result=await post(resetting?'/api/auth/reset-password':'/api/auth/forgot-password',resetting?{token,password}:{email});
     setDone(true);setMessage(result.message||'Request complete.');setPassword('');setConfirm('');
   }catch(e){setError((e as Error).message)}finally{setBusy(false)}
 }
 return <div className="min-h-screen bg-background flex flex-col">
   <header className="flex items-center justify-between px-5 sm:px-10 py-6"><Logo/><ThemeToggle/></header>
   <main className="grow flex items-center justify-center px-4 py-16">
     <section className="w-full max-w-[470px] rounded-3xl border border-border bg-card/70 p-6 sm:p-10 shadow-xl" aria-labelledby="recover-title">
       <div className="h-12 w-12 rounded-2xl bg-primary/15 text-primary flex items-center justify-center mb-6"><KeyRound size={23}/></div>
       <h1 id="recover-title" className="text-3xl font-black tracking-tight">{resetting?'Choose a new password':'Forgot your password?'}</h1>
       <p className="mt-3 mb-7 text-sm text-muted-foreground">{resetting?'Choose a new password for your Larpdevice account. This link expires after 60 minutes and can be used once.':'Enter your account email. If it matches an account, we’ll email you a secure password reset link.'}</p>
       {done?<div className="space-y-5"><div role="status" className="rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-4 text-sm">{message}</div><p className="text-sm text-muted-foreground">{resetting?'Your existing sessions have been signed out.':'If the email doesn’t arrive, check spam or ask Support for help.'}</p><Button className="w-full h-11" asChild><Link href="/login">Back to sign in <ArrowRight size={16}/></Link></Button></div>:
       <form onSubmit={e=>void submit(e)} className="space-y-5">
         {!resetting?<div className="space-y-2"><Label htmlFor="recovery-email">Email address</Label><div className="relative"><Mail size={17} className="absolute left-3 top-3.5 text-muted-foreground"/><Input id="recovery-email" type="email" autoComplete="email" required maxLength={254} className="pl-10 h-12" placeholder="you@example.com" value={email} onChange={e=>setEmail(e.target.value)}/></div></div>:
         <><div className="space-y-2"><Label htmlFor="new-password">New password</Label><div className="relative"><Input id="new-password" type={show?'text':'password'} autoComplete="new-password" minLength={10} maxLength={128} required className="h-12 pr-11" placeholder="At least 10 characters" value={password} onChange={e=>setPassword(e.target.value)}/><button type="button" aria-label="Toggle password visibility" className="absolute right-3 top-3.5 text-muted-foreground" onClick={()=>setShow(x=>!x)}>{show?<EyeOff size={17}/>:<Eye size={17}/>}</button></div></div><div className="space-y-2"><Label htmlFor="confirm-password">Confirm new password</Label><Input id="confirm-password" type={show?'text':'password'} autoComplete="new-password" minLength={10} maxLength={128} required className="h-12" value={confirm} onChange={e=>setConfirm(e.target.value)}/></div></>}
         {error&&<div role="alert" className="rounded-xl bg-red-500/10 p-3 text-sm text-red-500">{error}</div>}
         <Button type="submit" variant="gradient" className="w-full h-12" disabled={busy}>{busy?'Please wait...':resetting?'Reset password':'Send reset link'}<ArrowRight size={16}/></Button>
       </form>}
       {!done&&<Link href={resetting?'/forgot-password':'/login'} className="mt-6 text-sm font-medium text-primary flex items-center justify-center gap-2"><ArrowLeft size={16}/>{resetting?'Request another link':'Back to sign in'}</Link>}
       <p className="mt-8 flex items-center justify-center gap-2 text-xs text-muted-foreground"><ShieldCheck size={14}/> Larpdevice will never ask for your password in an email.</p>
     </section>
   </main>
   <footer className="flex items-center justify-between px-5 sm:px-10 py-6 text-xs text-muted-foreground"><span>© Larpdevice</span><span><Link href="/support" className="hover:underline">Support</Link> · <Link href="/privacy" className="hover:underline">Privacy</Link></span></footer>
 </div>;
}
