'use client';
import {useState} from 'react';
import {SectionStepHeader} from '@/components/section-step-header';
import {debtNames,openingMonth,planMonthLabel} from '@/lib/financial-goals';
import {progressBaseline,goalProgress,monthOffset,validProgress} from '@/lib/financial-progress';
const money=(v:number)=>new Intl.NumberFormat('en-ZA',{style:'currency',currency:'ZAR',maximumFractionDigits:2}).format(v);
export function FinancialProgress({p,state,change,navigate}:any){const [month,setMonth]=useState(openingMonth),[draft,setDraft]=useState<Record<string,string>>({}),[error,setError]=useState(''),[notice,setNotice]=useState('');const saved=p.financialProgress,baseline=saved?.baseline?{...saved.baseline,goals:saved.baseline.goals.map((goal:any)=>{const i=['home','car','cards'].indexOf(goal.id);return i<0?goal:{...goal,name:debtNames(state.input.goals)[i]};})}:progressBaseline(state),goals=baseline.goals,record=saved?.months?.[month],offset=monthOffset(baseline.start,month);function save(){const values:Record<string,number>={};for(const g of goals){const raw=draft[g.id]??(record?.[g.id]===undefined?'':String(record[g.id]));if(!raw.trim()||!Number.isFinite(Number(raw))||Number(raw)<0){setError('Enter a current amount for every goal. Use 0 only when the balance is zero.');return;}values[g.id]=Number(raw);}const next={baseline,months:{...saved?.months,[month]:values}};if(!validProgress(next)){setError('Choose a month from your plan’s starting month up to this month.');return;}change((x:any)=>x.financialProgress=next);setDraft({});setError('');setNotice('Monthly check-in updated. Check the save status at the top before closing.');}
return <section className="panel financialprogress" id="finance-progress"><SectionStepHeader step={3} title="Look How Far You’ve Come">Choose your check-in month, enter each goal’s actual balance at month end, then save your check-in to see how you are progressing.</SectionStepHeader><p className="note">Use your actual savings and outstanding debt balances. Uploading a budget does not fill in these amounts.</p>{!goals.length?<div className="progresssetup"><label className="field progressmonth"><span>Check-In Month</span><input type="month" value={month} disabled/><small>Available once you have a goal to track.</small></label><p>Add a savings, debt or cash-flow goal in step 2 to begin. Complete any missing plan details listed below.</p>{!!state.errors?.length&&<ul>{state.errors.map((message:string)=><li key={message}>{message}</li>)}</ul>}<button className="secondary" onClick={()=>navigate('goals')}>Go To My Goals</button><button className="secondary" onClick={()=>navigate('budget')}>Review My Budget</button></div>:<><p className="note">{saved?'Your comparison stays anchored to the plan saved at your first check-in, even when your budget changes.':'Your first check-in keeps a copy of the selected plan as your starting point.'} Cash-flow goals without a deadline show progress towards the target, rather than a monthly schedule.</p>{baseline.feasible===false&&<p className="progresshelp">Your selected plan does not yet meet every target date or required payment. The comparisons below show whether you match that projection; revisit your goals and available budget to improve the plan.</p>}<label className="field progressmonth"><span>Check-In Month</span><input type="month" min={baseline.start} max={openingMonth()} value={month} onChange={e=>{if(!e.target.value)return;setMonth(e.target.value);setDraft({});setError('');setNotice('');}}/></label><div className="progressgoals">{goals.map((g:any)=>{const result=goalProgress(g,offset,record?.[g.id]);return <article className="progressgoal" key={g.id}><div className="between"><h3>{g.name}</h3><span className={'progressstatus '+(result.status==='Needs Attention'?'attention':'')}>{result.status}</span></div><p className="note">Starting point: {money(g.opening)} · Target: {money(g.target)}{g.due!==null?' by '+planMonthLabel(baseline.start,g.due):''}</p><div className="mini"><div><span>Planned By Month End</span><b>{result.planned===null?'No Monthly Schedule':money(result.planned)}</b></div><div><span>Your Recorded Amount</span><b>{record?.[g.id]===undefined?'Not Entered':money(record[g.id])}</b></div></div>{result.percent!==null&&<><div className="track" role="progressbar" aria-label={g.name+' progress'} aria-valuenow={Math.round(result.percent)} aria-valuemin={0} aria-valuemax={100}><div style={{width:result.percent+'%'}}/></div><p className="progresscaption">{Math.round(result.percent)}% of the journey from your starting point</p></>}{result.status==='Needs Attention'&&<p className="progresshelp">{money(Math.abs(result.difference!))} behind this month’s plan. Review what you can put towards this goal, or adjust its timing.</p>}<label className="field"><span>{g.direction==='down'?'Actual Outstanding Balance':g.id==='cashflow'?'Monthly Cash Flow Freed Up':'Actual Current Balance'}</span><div className="number"><span>R</span><input type="number" min={0} step="0.01" aria-label={g.name+' actual amount'} value={draft[g.id]??(record?.[g.id]===undefined?'':String(record[g.id]))} placeholder="Enter your actual amount" onChange={e=>setDraft({...draft,[g.id]:e.target.value})}/></div></label></article>})}</div>{error&&<p className="error" role="alert">{error}</p>}{notice&&<p role="status">{notice}</p>}<button className="primarybutton" onClick={save}>{record?'Update Monthly Check-In':'Save Monthly Check-In'}</button>{saved&&<><details className="progresshistory"><summary>Previous Monthly Check-Ins</summary>{Object.keys(saved.months).sort().reverse().map(m=><button className="secondary" key={m} onClick={()=>{setMonth(m);setDraft({});setNotice('');}}>{new Date(m+'-01T12:00:00Z').toLocaleDateString('en-ZA',{timeZone:'UTC',month:'long',year:'numeric'})}</button>)}</details><button className="textbutton" onClick={()=>{if(window.confirm('Start a new progress plan? This removes your recorded check-ins from this view. Your budget and financial goals stay unchanged.')){change((x:any)=>delete x.financialProgress);setDraft({});setMonth(openingMonth());setNotice('');setError('');}}}>Start A New Progress Plan</button></>}</>}</section>;
}
