'use client';
import {useEffect,useRef,useState,type FormEvent,type InputHTMLAttributes} from 'react';
import {ArrowLeft,ArrowRight,Check,Eye,EyeOff,KeyRound,LoaderCircle,Mail,ShieldCheck,Smartphone,UserRound,UserRoundPlus} from 'lucide-react';
import {Tabs,TabsList,TabsTrigger,TabsContent} from './ui/tabs';
import {Checkbox} from './ui/checkbox';
import {InputOTP,InputOTPGroup,InputOTPSlot} from './ui/input-otp';
import {referralCode,referralCookie} from '@/lib/referrals';
import {latinDigits,normalizePhone,type CustomerUser} from '@/lib/auth-input';

type View='entry'|'verify'|'forgot'|'email-sent'|'reset';
type Intent='login'|'register'|'recover';
type RegistrationMode='direct-test'|'sms'|'sandbox';
type Reply={user?:CustomerUser;notice?:string;message?:string;error?:string;phone?:string;step?:string;verificationMode?:'sandbox'|'sms';testCode?:string};
export type AuthInitialView='entry'|'reset'|'recovery-error';

function PasswordField({label='رمز عبور',name='password',fresh=false,...props}:InputHTMLAttributes<HTMLInputElement>&{label?:string;fresh?:boolean}){
 const [visible,setVisible]=useState(false);
 return <label className="auth-field"><span>{label}</span><div className="auth-input-wrap"><KeyRound size={17} aria-hidden="true"/><input {...props} name={name} type={visible?'text':'password'} dir="ltr" autoComplete={fresh?'new-password':'current-password'} required minLength={fresh?12:undefined} maxLength={256} placeholder={fresh?'حداقل ۱۲ نویسه':'رمز عبور خود را وارد کنید'}/><button type="button" className="password-eye" aria-label={visible?'پنهان کردن رمز عبور':'نمایش رمز عبور'} aria-pressed={visible} onClick={()=>setVisible(v=>!v)}>{visible?<EyeOff size={18}/>:<Eye size={18}/>}</button></div></label>;
}
function PhoneField({value,contactOnly=false}:{value?:string;contactOnly?:boolean}){
 return <label className="auth-field"><span>شماره موبایل</span><div className="auth-input-wrap"><Smartphone size={17} aria-hidden="true"/><input name="phone" type="tel" inputMode="tel" autoComplete="tel" placeholder="۰۹۱۲ ۱۲۳ ۴۵۶۷" dir="ltr" required maxLength={40} defaultValue={value}/></div><small>{contactOnly?'شماره شما در حساب ثبت می‌شود، اما مالکیت آن در این مرحله با پیامک بررسی نمی‌شود. ':''}برای شماره‌های خارج از ایران، کد کشور را وارد کنید.</small></label>;
}
function Submit({busy,children,disabled=false}:{busy:boolean;children:React.ReactNode;disabled?:boolean}){
 return <button type="submit" className="primary-button auth-submit" disabled={busy||disabled}>{busy?<><LoaderCircle size={18} className="auth-spinner"/>در حال انجام…</>:<>{children}<ArrowLeft size={17}/></>}</button>;
}
export function CustomerAuth({onAuthenticated,initialView='entry'}:{onAuthenticated:(user:CustomerUser,notice?:string)=>void;initialView?:AuthInitialView}){
 const [referral,setReferral]=useState('');
 const [registrationMode,setRegistrationMode]=useState<RegistrationMode|null>(null),[sandboxVerification,setSandboxVerification]=useState(false),[modeUnavailable,setModeUnavailable]=useState(false);
 useEffect(()=>{let active=true;fetch('/api/auth/mode').then(async response=>{if(!response.ok)throw new Error('mode-unavailable');return response.json() as Promise<{registrationMode?:string}>}).then(data=>{if(data.registrationMode!=='direct-test'&&data.registrationMode!=='sms'&&data.registrationMode!=='sandbox')throw new Error('mode-unavailable');if(active)setRegistrationMode(data.registrationMode)}).catch(()=>{if(active)setModeUnavailable(true)});return()=>{active=false}},[]);
 const sandboxRegistration=registrationMode==='sandbox',directRegistration=registrationMode==='direct-test';
 const smsAvailable=registrationMode==='sms'||sandboxRegistration;
 useEffect(()=>{const url=new URL(window.location.href);const ref=referralCookie(document.cookie)||referralCode(url.searchParams.get('ref'));if(ref)setReferral(ref);if(url.searchParams.get('auth')==='register')setTab('register')},[]);
 const [tab,setTab]=useState('login'),[method,setMethod]=useState('password');
 const [view,setView]=useState<View>(initialView==='reset'?'reset':initialView==='recovery-error'?'forgot':'entry');
 const [intent,setIntent]=useState<Intent>('login'),[phone,setPhone]=useState(''),[code,setCode]=useState(''),[remember,setRemember]=useState(false);
 const [busy,setBusy]=useState(false),[error,setError]=useState(initialView==='recovery-error'?'لینک بازیابی معتبر نیست یا زمان آن تمام شده است. دوباره درخواست بدهید.':''),[notice,setNotice]=useState('');
 const [cooldown,setCooldown]=useState(0);const resendAt=useRef(0),inFlight=useRef(false),errorRef=useRef<HTMLParagraphElement>(null);
 useEffect(()=>{const update=()=>setCooldown(Math.max(0,Math.ceil((resendAt.current-Date.now())/1000)));const timer=setInterval(update,1000);return()=>clearInterval(timer)},[]);
 useEffect(()=>{if(error)errorRef.current?.focus()},[error]);
 const resetMessages=()=>{setError('');setNotice('')};
 function back(){resetMessages();setCode('');setView('entry');setIntent('login')}
 async function perform(path:string,payload:Record<string,unknown>,next:(data:Reply)=>void){
  if(inFlight.current)return;inFlight.current=true;setBusy(true);resetMessages();
  try{
   const response=await fetch('/api/auth/'+path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
   const data=await response.json() as Reply;
   if(!response.ok)throw new Error(data.error||'درخواست انجام نشد. دوباره تلاش کنید.');
   next(data);
  }catch(e){setError(e instanceof Error?e.message:'ارتباط برقرار نشد. دوباره تلاش کنید.')}
  finally{inFlight.current=false;setBusy(false)}
 }
 function beginVerify(data:Reply,nextIntent:Intent){setPhone(data.phone||phone);setIntent(nextIntent);setCode('');setSandboxVerification(data.verificationMode==='sandbox');setView('verify');resendAt.current=Date.now()+60000;setCooldown(60)}
 function accept(data:Reply){if(data.user)onAuthenticated(data.user,data.notice);else setError('ورود کامل نشد. دوباره تلاش کنید.')}
 function login(e:FormEvent<HTMLFormElement>){e.preventDefault();const fields=new FormData(e.currentTarget);void perform('login',{identifier:fields.get('identifier'),password:fields.get('password'),remember},accept)}
 function register(e:FormEvent<HTMLFormElement>){e.preventDefault();const fields=new FormData(e.currentTarget);void perform('register',Object.fromEntries(fields),data=>{if(data.user){accept(data);return}if(!directRegistration){beginVerify(data,'register');return}setError('ثبت‌نام کامل نشد. لطفاً دوباره تلاش کنید.')})}
 function sendPhone(e:FormEvent<HTMLFormElement>){e.preventDefault();const fields=new FormData(e.currentTarget);void perform('otp',{action:'send',phone:fields.get('phone'),intent:'login'},data=>beginVerify(data,'login'))}
 function verify(e:FormEvent<HTMLFormElement>){e.preventDefault();void perform('otp',{action:'verify',phone,code,intent,remember},data=>{if(data.step==='reset'){setCode('');setView('reset')}else accept(data)})}
 function recover(e:FormEvent<HTMLFormElement>){
  e.preventDefault();const identifier=String(new FormData(e.currentTarget).get('identifier')||'');
  const recoveryPhone=normalizePhone(identifier);
  if(recoveryPhone&&smsAvailable)void perform('otp',{action:'send',phone:recoveryPhone,intent:'recover'},data=>beginVerify(data,'recover'));
  else void perform('recovery',{action:'request',email:identifier},data=>{setNotice(data.message||'');setView('email-sent')});
 }
 function changePassword(e:FormEvent<HTMLFormElement>){
  e.preventDefault();const fields=new FormData(e.currentTarget);
  if(fields.get('password')!==fields.get('confirmation')){setError('رمز جدید و تکرار آن یکسان نیستند.');return}
  void perform('recovery',{action:'reset',password:fields.get('password')},data=>{setView('entry');setTab('login');setMethod('password');setNotice(data.message||'')});
 }
 const rememberControl=<label className="auth-remember"><Checkbox checked={remember} onCheckedChange={setRemember} disabled={busy}/><span>ذخیره اطلاعات کاربری</span></label>;
 return <div className="customer-auth" aria-busy={busy}>
  {view==='entry'&&<Tabs value={tab} onValueChange={value=>{setTab(String(value));resetMessages()}} className="auth-tabs">
   <TabsList className="auth-main-tabs" aria-label="ورود یا ثبت‌نام"><TabsTrigger value="login" disabled={busy}><UserRound size={17}/>ورود</TabsTrigger><TabsTrigger value="register" disabled={busy}><UserRoundPlus size={17}/>ثبت‌نام</TabsTrigger></TabsList>
   <TabsContent value="login"><Tabs value={method} onValueChange={value=>{setMethod(String(value));resetMessages()}} className="auth-method-tabs">
    <TabsList className="auth-methods" aria-label="روش ورود"><TabsTrigger value="password" disabled={busy}><KeyRound size={15}/>رمز عبور</TabsTrigger>{smsAvailable&&<TabsTrigger value="phone" disabled={busy}><Smartphone size={15}/>کد یک‌بارمصرف</TabsTrigger>}</TabsList>
    <TabsContent value="password"><form className="auth-form" onSubmit={login}><fieldset disabled={busy}>
     <label className="auth-field"><span>نام کاربری، ایمیل یا شماره موبایل</span><div className="auth-input-wrap"><UserRound size={17} aria-hidden="true"/><input name="identifier" autoComplete="username" autoCapitalize="none" spellCheck={false} required maxLength={254} placeholder="ایمیل، موبایل یا نام کاربری شما" dir="auto"/></div></label>
     <PasswordField/>
     <div className="auth-options">{rememberControl}<button type="button" className="auth-text-button" onClick={()=>{resetMessages();setView('forgot')}}>فراموشی رمز عبور</button></div>
     <Submit busy={busy}>ورود به حساب</Submit>
    </fieldset></form></TabsContent>
    {smsAvailable&&<TabsContent value="phone"><form className="auth-form" onSubmit={sendPhone}><fieldset disabled={busy}>
     <p className="auth-description">با کدی که به موبایل شما ارسال می‌شود وارد شوید.</p><PhoneField value={phone}/>{rememberControl}<Submit busy={busy}>دریافت کد ورود</Submit>
    </fieldset></form></TabsContent>}
   </Tabs></TabsContent>
   <TabsContent value="register"><form className="auth-form" onSubmit={register}><fieldset disabled={busy||!registrationMode}>
    {!registrationMode&&<p className="auth-description" role="status">{modeUnavailable?'امکان دریافت تنظیمات ثبت‌نام وجود ندارد. لطفاً صفحه را دوباره بارگذاری کنید.':'در حال آماده‌سازی ثبت‌نام…'}</p>}
    {sandboxRegistration&&<p className="auth-description" role="status">ثبت‌نام آزمایشی فعال است. پس از وارد کردن شمارهٔ خود، کد <strong dir="ltr">۱۲۳۴۵۶</strong> را وارد کنید؛ فعلاً پیامک ارسال نمی‌شود.</p>}
    {directRegistration&&<p className="auth-description" role="status">ثبت‌نام آزمایشی؛ فعلاً تأیید پیامکی انجام نمی‌شود.</p>}
    {smsAvailable&&<div className="auth-steps" aria-label="مرحله ۱ از ۲"><span className="active"><b>۱</b>اطلاعات شما</span><i/><span><b>۲</b>تأیید موبایل</span></div>}
    <div className="auth-name-grid"><label className="auth-field"><span>نام</span><input name="firstName" autoComplete="given-name" placeholder="نام شما" required maxLength={80}/></label><label className="auth-field"><span>نام خانوادگی</span><input name="lastName" autoComplete="family-name" placeholder="نام خانوادگی شما" required maxLength={80}/></label></div>
    <label className="auth-field"><span>ایمیل</span><div className="auth-input-wrap"><Mail size={17} aria-hidden="true"/><input type="email" name="email" autoComplete="email" placeholder="you@example.com" required maxLength={254} dir="ltr"/></div></label>
    <PhoneField value={phone} contactOnly={directRegistration}/>
    <label className="auth-field"><span>نام کاربری دلخواه <small>اختیاری</small></span><input name="username" autoComplete="username" autoCapitalize="none" spellCheck={false} minLength={3} maxLength={32} pattern="[a-zA-Z][a-zA-Z0-9_]{2,31}" dir="ltr" placeholder="your_username"/><small>{directRegistration?'برای ورود به حساب از شماره موبایل و رمز عبور استفاده کنید.':'می‌توانید با شماره موبایل یا ایمیل تأییدشده وارد شوید.'} نام دلخواه فقط با حروف انگلیسی، عدد و زیرخط ساخته می‌شود.</small></label>
<label className="auth-field"><span>کد دعوت <small>اختیاری</small></span><input name="referralCode" dir="ltr" autoCapitalize="none" spellCheck={false} autoComplete="off" maxLength={8} placeholder="plk234mf" value={referral} onChange={e=>setReferral(e.target.value.toLowerCase())}/></label>
    <PasswordField fresh/>
    <Submit busy={busy} disabled={!registrationMode}>{!registrationMode?'ثبت‌نام':directRegistration?'ثبت‌نام و ورود':sandboxRegistration?'ادامه و تأیید شماره موبایل':'ادامه و دریافت کد تأیید'}</Submit>
   </fieldset></form></TabsContent>
  </Tabs>}
  {view==='verify'&&<form className="auth-form auth-verify" onSubmit={verify}><fieldset disabled={busy}>
   <div className="auth-verification-icon"><ShieldCheck size={28}/></div><h3>{intent==='register'?'تأیید شماره موبایل':'کد تأیید را وارد کنید'}</h3><p className="auth-description">{sandboxVerification?'تأیید آزمایشی شمارهٔ ':'کد ارسال‌شده به '}<b dir="ltr">{phone}</b>{sandboxVerification?'':' را وارد کنید.'}</p>
   <div dir="ltr" className="auth-otp"><InputOTP maxLength={6} value={code} onChange={value=>setCode(latinDigits(value).replace(/\D/g,''))} pasteTransformer={value=>latinDigits(value).replace(/\D/g,'')} autoFocus inputMode="numeric" autoComplete="one-time-code" aria-label="کد تأیید پیامک، حداکثر شش رقم" disabled={busy}><InputOTPGroup>{Array.from({length:6},(_,i)=><InputOTPSlot index={i} key={i}/>)}</InputOTPGroup></InputOTP></div>
   <p className="auth-description">{sandboxVerification?<>کد موقت: <strong dir="ltr">۱۲۳۴۵۶</strong> — پیامک واقعی ارسال نشده است.</>:'کد را همان‌طور که در پیامک آمده وارد کنید.'}</p>{intent!=='recover'&&rememberControl}<Submit busy={busy} disabled={code.length<1}>{intent==='register'?'تأیید و ساخت حساب':intent==='recover'?'تأیید و تعیین رمز جدید':'تأیید و ورود'}</Submit>
   <div className="auth-resend"><button type="button" className="auth-text-button" disabled={busy||cooldown>0} onClick={()=>void perform('otp',{action:'resend',phone,intent},data=>beginVerify(data,intent))}>{cooldown>0?`ارسال مجدد تا ${new Intl.NumberFormat('fa').format(cooldown)} ثانیه دیگر`:'ارسال مجدد کد'}</button><button type="button" className="auth-text-button" disabled={busy} onClick={()=>{resetMessages();setCode('');setView(intent==='recover'?'forgot':'entry');setTab(intent==='register'?'register':'login');setMethod('phone')}}>ویرایش شماره</button></div>
  </fieldset></form>}
  {view==='forgot'&&<form className="auth-form" onSubmit={recover}><fieldset disabled={busy}><h3>بازیابی رمز عبور</h3><p className="auth-description">{smsAvailable?'ایمیل یا شماره موبایل حساب خود را وارد کنید.':'ایمیل متصل به حساب خود را وارد کنید تا لینک بازیابی برایتان ارسال شود.'}</p><label className="auth-field"><span>{smsAvailable?'ایمیل یا شماره موبایل':'ایمیل'}</span><div className="auth-input-wrap"><Mail size={17}/><input name="identifier" type={smsAvailable?'text':'email'} autoComplete={smsAvailable?'username':'email'} required maxLength={254} placeholder={smsAvailable?'ایمیل یا موبایل شما':'you@example.com'} dir={smsAvailable?'auto':'ltr'}/></div></label><Submit busy={busy}>دریافت راهنمای بازیابی</Submit><button type="button" className="auth-back" onClick={back}><ArrowRight size={15}/>بازگشت به ورود</button></fieldset></form>}
  {view==='email-sent'&&<div className="auth-status"><div className="auth-verification-icon"><Mail size={28}/></div><h3>ایمیل خود را بررسی کنید</h3><p>{notice}</p><button className="secondary-button" onClick={back}>بازگشت به ورود</button></div>}
  {view==='reset'&&<form className="auth-form" onSubmit={changePassword}><fieldset disabled={busy}><h3>رمز عبور جدید</h3><p className="auth-description">رمزی انتخاب کنید که در حساب‌های دیگر استفاده نکرده‌اید.</p><PasswordField fresh label="رمز عبور جدید"/><PasswordField fresh label="تکرار رمز عبور جدید" name="confirmation"/><Submit busy={busy}>ذخیره رمز جدید</Submit><button type="button" className="auth-back" onClick={()=>{resetMessages();setView('forgot')}}>دریافت مجدد لینک یا کد بازیابی</button></fieldset></form>}
  {error&&<p ref={errorRef} tabIndex={-1} className="form-error auth-feedback" role="alert">{error}</p>}
  {notice&&view!=='email-sent'&&<p className="auth-success" role="status"><Check size={16}/>{notice}</p>}
  <p className="auth-security-note"><ShieldCheck size={14}/>ورود امن به حساب پلانک شما</p>
 </div>;
}

export function ConnectEmail(){
 const [busy,setBusy]=useState(false),[error,setError]=useState(''),[message,setMessage]=useState('');
 return <form className="auth-form" onSubmit={async e=>{e.preventDefault();const email=new FormData(e.currentTarget).get('email');setBusy(true);setError('');setMessage('');try{const response=await fetch('/api/auth/email',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email})});const data=await response.json() as Reply;if(!response.ok)throw new Error(data.error);setMessage(data.message||'')}catch(e){setError((e as Error).message)}finally{setBusy(false)}}}><label className="auth-field"><span>اتصال ایمیل به حساب</span><input type="email" name="email" dir="ltr" autoComplete="email" required maxLength={254} placeholder="you@example.com"/></label><button className="secondary-button" disabled={busy}>{busy?'در حال ارسال…':'ارسال تأیید ایمیل'}</button>{error&&<p className="form-error" role="alert">{error}</p>}{message&&<p className="auth-success" role="status">{message}</p>}</form>;
}
