"use client";
import { useMemo,useState } from "react";
type Project={id:number;name:string;contractValue:number;status:string};type Entry={id:number;date:string;dueDate:string;category:string;direction:string;description:string;amount:number;paidAmount:number;status:string};type Asset={acquisitionValue:number};type Data={projects:Project[];entries:Entry[];assets:Asset[]};type Alert=Entry&{days:number};
const today=new Date().toISOString().slice(0,10),monthStart=today.slice(0,8)+"01",rp=(n:number)=>new Intl.NumberFormat("id-ID",{style:"currency",currency:"IDR",maximumFractionDigits:0}).format(n||0),short=(n:number)=>n>=1e9?`Rp ${(n/1e9).toFixed(1)} M`:n>=1e6?`Rp ${(n/1e6).toFixed(0)} jt`:rp(n),fmt=(d:string)=>new Intl.DateTimeFormat("id-ID",{day:"2-digit",month:"short",year:"numeric"}).format(new Date(d+"T00:00:00"));
export default function FinanceDashboard({data,alerts,go}:{data:Data;income?:number;expense?:number;receivable?:number;payable?:number;alerts:Alert[];go:(s:string)=>void}){const[from,setFrom]=useState(monthStart),[to,setTo]=useState(today),rows=useMemo(()=>data.entries.filter(e=>e.date>=from&&e.date<=to),[data.entries,from,to]),income=rows.filter(e=>e.direction==="Masuk"&&e.category!=="Penawaran").reduce((a,e)=>a+e.paidAmount,0),expense=rows.filter(e=>e.direction==="Keluar").reduce((a,e)=>a+e.paidAmount,0),receivable=rows.filter(e=>e.direction==="Masuk"&&["Invoice","Piutang"].includes(e.category)).reduce((a,e)=>a+Math.max(0,e.amount-e.paidAmount),0),payable=rows.filter(e=>e.direction==="Keluar"&&["Hutang","Tagihan"].includes(e.category)).reduce((a,e)=>a+Math.max(0,e.amount-e.paidAmount),0),profit=income-expense,contract=data.projects.reduce((a,p)=>a+p.contractValue,0),assetValue=data.assets.reduce((a,x)=>a+x.acquisitionValue,0),cash=income-expense,totalAssets=cash+receivable+assetValue,equity=totalAssets-payable,balanceMax=Math.max(1,Math.abs(totalAssets),Math.abs(payable),Math.abs(equity)),recent=rows.slice(0,7),total=Math.max(1,income+expense),incomeDeg=Math.round(income/total*360);return <div className="executive-dashboard">
 <section className="executive-intro"><div><span>EXECUTIVE FINANCE OVERVIEW</span><h2>Ringkasan keuangan berdasarkan periode.</h2><p>Seluruh angka dihitung dari transaksi database pada tanggal yang dipilih.</p></div><div className="dashboard-range"><label>Dari<input type="date" value={from} onChange={e=>setFrom(e.target.value)}/></label><label>Sampai<input type="date" value={to} onChange={e=>setTo(e.target.value)}/></label></div></section>
 <section className="metric-cards"><Metric tone="cyan" label="Total Penerimaan" value={rp(income)} note="Kas masuk terealisasi"/><Metric tone="violet" label="Total Pengeluaran" value={rp(expense)} note="Biaya proyek & operasi"/><Metric tone="blue" label="Laba / Rugi" value={rp(profit)} note={profit>=0?"Posisi surplus":"Posisi defisit"}/><Metric tone="amber" label="Nilai Kontrak" value={rp(contract)} note={`${data.projects.filter(p=>p.status==="Berjalan").length} proyek berjalan`}/></section>
 <section className="analytics-grid"><article className="analytics-card"><div className="analytics-head"><div><h3>Komposisi Kas</h3><p>{fmt(from)} — {fmt(to)}</p></div></div><div className="donut-wrap"><div className="donut" style={{background:`conic-gradient(#12a9cf 0deg ${incomeDeg}deg,#786fe8 ${incomeDeg}deg 360deg)`}}><div><strong>{Math.round(income/total*100)}%</strong><small>Kas masuk</small></div></div><div className="donut-data"><p><i className="cash-in"/><span>Penerimaan</span><b>{short(income)}</b></p><p><i className="cash-out"/><span>Pengeluaran</span><b>{short(expense)}</b></p><p className="net"><span>Saldo bersih</span><b className={profit>=0?"up":"down"}>{short(profit)}</b></p></div></div></article><article className="analytics-card balance-balloon"><div className="analytics-head"><div><h3>Ringkasan Neraca</h3><p>Aktiva = kewajiban + ekuitas</p></div><button onClick={()=>go("balance")}>Buka Neraca →</button></div><div className="balance-visual"><div><span>Total Aktiva</span><i><b style={{width:`${Math.abs(totalAssets)/balanceMax*100}%`}}/></i><strong>{short(totalAssets)}</strong></div><div><span>Hutang</span><i><b style={{width:`${Math.abs(payable)/balanceMax*100}%`}}/></i><strong>{short(payable)}</strong></div><div><span>Ekuitas</span><i><b style={{width:`${Math.abs(equity)/balanceMax*100}%`}}/></i><strong>{short(equity)}</strong></div></div><footer><span>Kas {short(cash)}</span><span>Piutang {short(receivable)}</span><span>Aset {short(assetValue)}</span></footer></article></section>
 <section className="overview-grid"><article className="analytics-card recent-card"><div className="analytics-head"><div><h3>Transaksi Periode</h3><p>Tampilan ringkas tanggal, jenis, dan jumlah</p></div><button onClick={()=>go("transactions")}>Lihat semua →</button></div><div className="dashboard-table compact"><table><thead><tr><th>Tanggal</th><th>Jenis transaksi</th><th>Jumlah</th></tr></thead><tbody>{recent.map(e=><tr key={e.id}><td>{fmt(e.date)}</td><td>{e.category} — {e.description}</td><td className="value">{rp(e.paidAmount||e.amount)}</td></tr>)}{!recent.length&&<tr><td colSpan={3}>Tidak ada transaksi pada periode ini.</td></tr>}</tbody></table></div></article><aside className="overview-side"><article className="analytics-card deadlines"><div className="analytics-head"><div><h3>Jatuh Tempo</h3><p>Perlu ditindaklanjuti</p></div><button onClick={()=>go("notifications")}>Detail</button></div>{alerts.slice(0,5).map(a=><div className="deadline-row" key={a.id}><span className={a.days<0?"late":""}>{a.days<0?"!":a.days}</span><div><strong>{a.description}</strong><small>{fmt(a.dueDate)}</small></div><b>{short(a.amount-a.paidAmount)}</b></div>)}</article></aside></section></div>}
function Metric({tone,label,value,note}:{tone:string;label:string;value:string;note:string}){return <article className={`metric-card ${tone}`}><span>●</span><div><p>{label}</p><h3>{value}</h3><small>{note}</small></div><em>•••</em></article>}

