'use client';
import {useState} from 'react';
import {History,RotateCcw} from 'lucide-react';
import {Dialog,DialogContent,DialogHeader,DialogTitle,DialogDescription} from './ui/dialog';
import type {PlanVersion} from '@/lib/plan-versions';
export function PlanHistory({projectId,userId,revision,dirty,busy,onOpenChange,onRestore}:{projectId:string;userId:string;revision:number;dirty:boolean;busy:boolean;onOpenChange:(open:boolean)=>void;onRestore:(version:number)=>Promise<void>}){
 const [open,setOpen]=useState(false),[loading,setLoading]=useState(false),[restoring,setRestoring]=useState(false),[error,setError]=useState(''),[rows,setRows]=useState<PlanVersion[]>([]),[current,setCurrent]=useState<PlanVersion|null>(null),[selected,setSelected]=useState<PlanVersion|null>(null);
 async function refresh(){setLoading(true);setError('');setSelected(null);setRows([]);setCurrent(null);try{const r=await fetch('/api/plan-history?projectId='+encodeURIComponent(projectId),{cache:'no-store',signal:AbortSignal.timeout(15000)}),d=await r.json() as {userId:string;projectId:string;current:PlanVersion;versions:PlanVersion[];error?:string};if(!r.ok||d.userId!==userId||d.projectId!==projectId)throw Error(d.error||'A fiók vagy a projekt megváltozott.');setCurrent(d.current);setRows(d.versions)}catch(e){setError(e instanceof Error?e.message:'A lista nem tölthető be.')}finally{setLoading(false)}}
 function toggle(value:boolean){if(restoring)return;setOpen(value);onOpenChange(value);if(value)void refresh()}
 async function restore(){if(!selected)return;setRestoring(true);setError('');try{await onRestore(selected.revision);setOpen(false);onOpenChange(false)}catch(e){setError(e instanceof Error?e.message:'Nem sikerült visszaállítani.')}finally{setRestoring(false)}}
 const stale=!!current&&current.revision!==revision,blocked=busy||loading||restoring||dirty||stale;
 return <><button disabled={busy||!revision} title={!revision?'Előbb mentsd el a projektet.':'Korábbi szervermentések'} onClick={()=>toggle(true)}><History/> Tervelőzmények</button><Dialog open={open} onOpenChange={toggle}><DialogContent className="plan-history-dialog"><DialogHeader><DialogTitle>Tervelőzmények</DialogTitle><DialogDescription>Az aktuális terv mellett az utolsó 30 korábbi szervermentést őrizzük meg. A kézi és automatikus mentések is ide kerülnek. A visszaállítás új mentést készít ugyanebben a projektben.</DialogDescription></DialogHeader>
 {dirty&&<p role="alert" className="auth-error">Mentetlen módosításaid vannak. Zárd be ezt az ablakot és mentsd el a tervet a visszaállítás előtt.</p>}{stale&&<p role="alert" className="auth-error">A szerveren újabb változat van. Nyisd meg újra a projektet a Projektek menüben.</p>}
 {error&&<p className="auth-error" role="alert">{error}</p>}<button disabled={loading||restoring} onClick={()=>void refresh()}>Lista frissítése</button>
 {loading?<p role="status">Tervelőzmények betöltése…</p>:<>{current&&<div className="history-current"><b>Jelenlegi változat · {current.revision}.</b><span>{current.name}</span><small>{new Date(current.savedAt).toLocaleString('hu-HU')}</small></div>}{!rows.length&&current&&<p>Még nincs korábbi mentés. A következő mentés előtt a jelenlegi változat ide kerül.</p>}
 {selected&&<div className="project-state-confirm"><b>{selected.revision}. változat visszaállítása</b><p>{selected.name} · {new Date(selected.savedAt).toLocaleString('hu-HU')}</p><p>Ez lesz az aktuális terv. A mostani szervermentés bekerül az előzményekbe; a legrégebbi a 30-as korlátnál kieshet.</p><div className="project-actions"><button disabled={restoring} onClick={()=>setSelected(null)}>Mégse</button><button className="primary" disabled={blocked} onClick={()=>void restore()}>{restoring?'Visszaállítás…':'Változat visszaállítása'}</button></div></div>}
 <div className="history-list">{rows.map(v=><div key={v.revision}><span><b>{v.revision}. · {v.name}</b><small>{new Date(v.savedAt).toLocaleString('hu-HU')}</small></span><button disabled={blocked||!!selected} aria-label={v.revision+'. változat visszaállítása'} onClick={()=>setSelected(v)}><RotateCcw/> Visszaállítás</button></div>)}</div></>}
 <p className="report-note">A frissítés előtti régebbi mentések nem állíthatók elő utólag. A háttéralaprajzokhoz az eredeti háttérfájlnak elérhetőnek kell maradnia. Az archivált vagy lomtárban lévő projektet előbb az Aktív listába kell visszaállítani.</p>
 </DialogContent></Dialog></>;
}
