"use client";
import {EmailVerification} from './email-verification';
import {useEffect,useState} from 'react';
import {CookieSettingsButton} from './cookie-notice';
import {UserRound,LogIn,LogOut,Database,Eye,EyeOff} from 'lucide-react';
import {Dialog,DialogContent,DialogHeader,DialogTitle,DialogDescription} from '@/components/ui/dialog';
export type Account={userId:string;displayName:string;email:string;emailVerified?:boolean}|null;
export function AccountMenu({account,onAuthenticated,dirty,save,storeDraft,dbState,initialOpen=false}:{account:Account;onAuthenticated:()=>void;dirty:boolean;save:()=>Promise<boolean>;storeDraft:()=>boolean;dbState:string;initialOpen?:boolean}){
 const[open,setOpen]=useState(initialOpen),[busy,setBusy]=useState(false),[mode,setMode]=useState<'login'|'register'>('login');
 const[name,setName]=useState(''),[email,setEmail]=useState(''),[password,setPassword]=useState(''),[repeat,setRepeat]=useState(''),[visible,setVisible]=useState(false),[error,setError]=useState('');
 useEffect(()=>{const params=new URLSearchParams(location.search);const auth=params.get('auth');if(auth==='login'||auth==='register'){setMode(auth);setOpen(true);params.delete('auth');history.replaceState(null,'',location.pathname+(params.size?'?'+params:'')+location.hash)}},[]);
 function switchMode(next:'login'|'register'){setMode(next);setError('');setPassword('');setRepeat('')}
 async function submit(e:React.FormEvent){
  e.preventDefault();if(busy)return;setError('');
  if(mode==='register'&&password!==repeat){setError('A két jelszó nem egyezik.');return}
  if(!storeDraft()){setError('Exportáld a tervedet JSON-fájlba a belépés előtt, hogy a szerkesztés megmaradjon.');return}
  setBusy(true);
  try{const r=await fetch('/api/auth/'+mode,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email,password,...(mode==='register'?{name}:{})})});const result=await r.json() as {error?:string};if(!r.ok)throw Error(result.error||'Nem sikerült belépni.');setPassword('');setRepeat('');onAuthenticated()}
  catch(e){setError(e instanceof Error?e.message:'Nem sikerült belépni.');setBusy(false)}
 }
 async function logout(){if(busy)return;setBusy(true);setError('');try{if(dirty&&!await save()){setBusy(false);return}const r=await fetch('/api/auth/logout',{method:'POST'});if(!r.ok)throw Error('A kijelentkezés nem sikerült. Próbáld újra.');onAuthenticated()}catch(e){setError(e instanceof Error?e.message:'Nem sikerült kijelentkezni.');setBusy(false)}}
 return <><button className="account-button" aria-label={account?'Fiók és adatbázis':'Bejelentkezés'} title={account?.displayName||'Bejelentkezés'} onClick={()=>{setOpen(true);setError('')}}>{account?<UserRound/>:<LogIn/>}<span>{account?'Fiókom':'Belépés'}</span></button>
 <Dialog open={open} onOpenChange={v=>{if(!busy){setOpen(v);setPassword('');setRepeat('')}}}><DialogContent className="account-dialog"><DialogHeader><DialogTitle>{account?'Saját fiók':mode==='register'?'Villanyrajz-fiók létrehozása':'Bejelentkezés'}</DialogTitle><DialogDescription>{account?'A mentett terv ehhez a fiókhoz tartozik.':mode==='register'?'Regisztrálj a saját e-mail-címeddel, és mentsd el a terveidet.':'Lépj be az e-mail-címeddel és a jelszavaddal.'}</DialogDescription></DialogHeader>
 {account?<><div className="account-identity"><UserRound/><div><strong>{account.displayName}</strong><span>{account.email}</span></div></div><EmailVerification initialVerified={!!account.emailVerified}/><div className="database-state"><Database/><div><b>Tervadatbázis</b><span>{dbState}</span></div></div><a className="account-help-link" href="/fiok/jelszo" target="_blank" rel="noopener noreferrer">Jelszó visszaállítása e-mailben ↗</a><p>Az alaprajzok, telki hálózatok és elosztók a saját fiókodban mentődnek.</p>{error&&<p className="auth-error" role="alert">{error}</p>}<button className="primary" disabled={busy} onClick={()=>void logout()}><LogOut/>{busy?'Kijelentkezés…':dirty?'Mentés és kijelentkezés':'Kijelentkezés'}</button></>:<><div className="auth-tabs" role="group" aria-label="Fiókművelet"><button className={mode==='login'?'active':''} disabled={busy} onClick={()=>switchMode('login')}>Bejelentkezés</button><button className={mode==='register'?'active':''} disabled={busy} onClick={()=>switchMode('register')}>Regisztráció</button></div>
 <form onSubmit={submit} className="auth-form">
 {mode==='register'&&<label className="field"><span>Név</span><input aria-label="Név" autoComplete="name" required maxLength={100} value={name} disabled={busy} onChange={e=>setName(e.target.value)}/></label>}
 <label className="field"><span>E-mail-cím</span><input aria-label="E-mail-cím" type="email" autoComplete="email" required maxLength={254} value={email} disabled={busy} onChange={e=>setEmail(e.target.value)}/></label>
 <label className="field"><span>Jelszó</span><div className="password-field"><input aria-label="Jelszó" type={visible?'text':'password'} autoComplete={mode==='register'?'new-password':'current-password'} required minLength={mode==='register'?12:undefined} value={password} disabled={busy} onChange={e=>setPassword(e.target.value)}/><button type="button" aria-label={visible?'Jelszó elrejtése':'Jelszó megjelenítése'} onClick={()=>setVisible(!visible)}>{visible?<EyeOff/>:<Eye/>}</button></div></label>
 {mode==='register'&&<><p className="password-hint">Legalább 12 karakter. Használhatsz hosszú jelmondatot is; a felső határ 72 bájt.</p><label className="field"><span>Jelszó ismét</span><input aria-label="Jelszó ismét" type={visible?'text':'password'} autoComplete="new-password" required value={repeat} disabled={busy} onChange={e=>setRepeat(e.target.value)}/></label></>}
 {error&&<p className="auth-error" role="alert">{error}</p>}<button className="primary" type="submit" disabled={busy}><LogIn/>{busy?'Folyamatban…':mode==='register'?'Fiók létrehozása':'Belépés'}</button></form>{mode==='login'&&<a className="account-help-link" href="/fiok/jelszo" target="_blank" rel="noopener noreferrer">Elfelejtetted a jelszavad?</a>}<p className="auth-note">A tervező bejelentkezés után használható. Az első saját projekted ingyenes.</p></>}
 <nav className="account-legal" aria-label="Jogi tájékoztatók"><a href="/aszf" target="_blank" rel="noopener noreferrer">ÁSZF</a><a href="/adatvedelem" target="_blank" rel="noopener noreferrer">Adatvédelem</a><a href="/sutik" target="_blank" rel="noopener noreferrer">Sütik</a><CookieSettingsButton/></nav></DialogContent></Dialog></>
}
