"use client";
import {useMemo,useState} from "react";
type Entry={id:number;date:string;dueDate?:string;category:string;direction:string;description:string;amount:number;paidAmount:number;status:string;projectName?:string;clientName?:string};
type Asset={id:number;code:string;name:string;category:string;acquisitionDate:string;acquisitionValue:number;usefulLife:number;condition:string;location:string};
type Approval={reportType:string;period:string;status:string;approvedBy:string;approvedAt:string};
const today=new Date().toISOString().slice(0,10),rp=(n:number)=>new Intl.NumberFormat("id-ID",{style:"currency",currency:"IDR",maximumFractionDigits:0}).format(n||0),monthName=(m:string)=>new Intl.DateTimeFormat("id-ID",{month:"long",year:"numeric"}).format(new Date(`${m}-01T00:00:00`)),fmt=(d:string)=>d?new Intl.DateTimeFormat("id-ID",{day:"2-digit",month:"short",year:"numeric"}).format(new Date(d+"T00:00:00")):"—";
export default function BalanceSheet({entries,assets,approvals,role,onApprove,onStatus,onAdd}:{entries:Entry[];assets:Asset[];approvals:Approval[];role:"director"|"manager";onApprove:(type:"Neraca",period:string)=>void;onStatus:(entry:Entry,status:string)=>void;onAdd:(kind:"entry"|"asset")=>void}){
 const[month,setMonth]=useState(today.slice(0,7)),[view,setView]=useState<"summary"|"debts"|"assets"|"profit">("summary");
 const data=useMemo(()=>{const end=`${month}-31`,monthly=entries.filter(e=>e.date.startsWith(month)),cumulative=entries.filter(e=>e.date<=end),cashIn=cumulative.filter(e=>e.direction==="Masuk"&&e.category!=="Penawaran").reduce((a,e)=>a+e.paidAmount,0),cashOut=cumulative.filter(e=>e.direction==="Keluar").reduce((a,e)=>a+e.paidAmount,0),cash=cashIn-cashOut,receivableRows=cumulative.filter(e=>e.direction==="Masuk"&&["Invoice","Piutang"].includes(e.category)),payableRows=cumulative.filter(e=>e.direction==="Keluar"&&["Hutang","Tagihan"].includes(e.category)),receivable=receivableRows.reduce((a,e)=>a+Math.max(0,e.amount-e.paidAmount),0),payable=payableRows.reduce((a,e)=>a+Math.max(0,e.amount-e.paidAmount),0),assetRows=assets.filter(a=>!a.acquisitionDate||a.acquisitionDate<=end),bookValue=(a:Asset)=>{if(!a.acquisitionDate||!a.usefulLife)return a.acquisitionValue;const acquired=new Date(`${a.acquisitionDate}T00:00:00`),asOf=new Date(`${month}-28T00:00:00`),months=Math.max(0,(asOf.getFullYear()-acquired.getFullYear())*12+asOf.getMonth()-acquired.getMonth());return Math.max(0,a.acquisitionValue*(1-months/(a.usefulLife*12)))},fixedAssets=assetRows.reduce((s,a)=>s+bookValue(a),0),revenue=monthly.filter(e=>e.direction==="Masuk"&&e.category!=="Penawaran").reduce((a,e)=>a+e.paidAmount,0),expense=monthly.filter(e=>e.direction==="Keluar").reduce((a,e)=>a+e.paidAmount,0),totalAssets=cash+receivable+fixedAssets,equity=totalAssets-payable;return{monthly,cash,receivableRows,payableRows,receivable,payable,assetRows,bookValue,fixedAssets,revenue,expense,profit:revenue-expense,totalAssets,equity}},[entries,assets,month]);
 const approval=approvals.find(a=>a.reportType==="Neraca"&&a.period===month);
 const DebtTable=({rows}:{rows:Entry[]})=><div className="table-wrap"><table><thead><tr><th>Tanggal</th><th>Jenis & Uraian</th><th>Relasi</th><th>Nilai</th><th>Terbayar</th><th>Sisa</th><th>Tahapan</th></tr></thead><tbody>{rows.map(e=><tr key={e.id}><td>{fmt(e.date)}</td><td><strong>{e.category}</strong><small>{e.description}</small></td><td>{e.clientName||e.projectName||"Umum"}</td><td>{rp(e.amount)}</td><td>{rp(e.paidAmount)}</td><td>{rp(Math.max(0,e.amount-e.paidAmount))}</td><td>{role==="manager"&&<select className="status-select no-print" value={["Draft","Revisi","Telah Dibayarkan"].includes(e.status)?e.status:"Draft"} onChange={x=>onStatus(e,x.target.value)}><option>Draft</option><option>Revisi</option><option>Telah Dibayarkan</option></select>}<span className={role==="manager"?"print-only":""}>{e.status}</span></td></tr>)}{!rows.length&&<tr><td colSpan={7}>Belum ada data.</td></tr>}</tbody></table></div>;
 return <section className="report-sheet balance-sheet"><div className="letterhead"><img src="/logo.png" alt="PT JLBB"/><div><h2>PT. JASA LINGKUNGAN BAHARI BATAM</h2><p>Komplek Ruko Golden City Blok RI 17, Batam, Kepulauan Riau</p></div></div><div className="balance-head"><div><span>LAPORAN KEUANGAN TERINTEGRASI</span><h1>NERACA & LABA BERJALAN</h1><p>Posisi keuangan sampai dengan periode {monthName(month)}</p><p className={`approval-state ${approval?"approved":"pending"}`}>{approval?`Disetujui ${approval.approvedBy} · ${fmt(approval.approvedAt.slice(0,10))}`:"Belum disetujui Direktur"}</p></div><div className="balance-controls no-print"><label>Periode Bulan<input type="month" value={month} onChange={e=>setMonth(e.target.value)}/></label>{role==="director"&&!approval&&<button className="approve-button" onClick={()=>onApprove("Neraca",month)}>✓ Setujui Neraca</button>}<button onClick={()=>window.print()}>⇩ Download PDF</button></div></div>
 <nav className="balance-tabs no-print">{[["summary","Ringkasan Neraca"],["debts","Hutang & Piutang"],["assets","Aset & Aktiva"],["profit","Laba Berjalan"]].map(([id,label])=><button key={id} className={view===id?"active":""} onClick={()=>setView(id as typeof view)}>{label}</button>)}</nav>
 {view==="summary"&&<div className="balance-section"><div className="balance-kpis"><article><span>KAS & BANK</span><strong>{rp(data.cash)}</strong><small>Penerimaan dikurangi pengeluaran terealisasi</small></article><article><span>PIUTANG USAHA</span><strong>{rp(data.receivable)}</strong><small>Hak tagih yang belum diterima</small></article><article><span>ASET TETAP BERSIH</span><strong>{rp(data.fixedAssets)}</strong><small>Estimasi nilai buku</small></article><article><span>HUTANG USAHA</span><strong>{rp(data.payable)}</strong><small>Kewajiban belum dibayar</small></article></div><div className="balance-columns"><article><h3>AKTIVA / ASET</h3><p><span>Kas dan bank</span><b>{rp(data.cash)}</b></p><p><span>Piutang usaha</span><b>{rp(data.receivable)}</b></p><p><span>Aset tetap—nilai buku</span><b>{rp(data.fixedAssets)}</b></p><p className="total"><span>TOTAL AKTIVA</span><b>{rp(data.totalAssets)}</b></p></article><article><h3>KEWAJIBAN & EKUITAS</h3><p><span>Hutang usaha</span><b>{rp(data.payable)}</b></p><p><span>Ekuitas / aset bersih</span><b>{rp(data.equity)}</b></p><p className="spacer"><span>&nbsp;</span><b>&nbsp;</b></p><p className="total"><span>TOTAL PASIVA</span><b>{rp(data.payable+data.equity)}</b></p></article></div><div className="balance-check"><span>Selisih keseimbangan neraca</span><strong className={Math.abs(data.totalAssets-(data.payable+data.equity))<1?"positive":"negative"}>{rp(data.totalAssets-(data.payable+data.equity))}</strong></div></div>}
 {view==="debts"&&<div className="balance-section"><div className="section-action no-print"><div><h2>Hutang & Piutang</h2><p>Saldo kewajiban dan hak tagih sampai akhir periode.</p></div><button onClick={()=>onAdd("entry")}>＋ Tambah Hutang / Piutang</button></div><div className="debt-totals"><article><span>TOTAL PIUTANG</span><strong>{rp(data.receivable)}</strong><small>Belum diterima</small></article><article><span>TOTAL HUTANG</span><strong>{rp(data.payable)}</strong><small>Belum dibayar</small></article><article><span>SELISIH BERSIH</span><strong>{rp(data.receivable-data.payable)}</strong><small>Piutang dikurangi hutang</small></article></div><h3 className="subsection-title">Daftar Piutang</h3><DebtTable rows={data.receivableRows}/><h3 className="subsection-title">Daftar Hutang</h3><DebtTable rows={data.payableRows}/></div>}
 {view==="assets"&&<div className="balance-section"><div className="section-action no-print"><div><h2>Register Aset & Aktiva</h2><p>Nilai perolehan dan estimasi nilai buku sampai akhir periode.</p></div><button onClick={()=>onAdd("asset")}>＋ Tambah Aset</button></div><div className="asset-summary"><span>Total nilai buku aset</span><strong>{rp(data.fixedAssets)}</strong></div><div className="asset-grid balance-assets">{data.assetRows.map(a=><article key={a.id}><div><span>{a.code}</span><b>{a.condition}</b></div><h3>{a.name}</h3><p>{a.category} • {a.location}</p><dl><div><dt>Nilai perolehan</dt><dd>{rp(a.acquisitionValue)}</dd></div><div><dt>Nilai buku periode</dt><dd>{rp(data.bookValue(a))}</dd></div><div><dt>Tanggal perolehan</dt><dd>{fmt(a.acquisitionDate)}</dd></div></dl></article>)}{!data.assetRows.length&&<p className="balance-empty">Belum ada aset tercatat.</p>}</div></div>}
 {view==="profit"&&<div className="balance-section"><div className="running-profit"><article><span>PENERIMAAN BULANAN</span><strong>{rp(data.revenue)}</strong></article><article><span>PENGELUARAN BULANAN</span><strong>{rp(data.expense)}</strong></article><article className={data.profit>=0?"profit":"loss"}><span>LABA / (RUGI) BERJALAN</span><strong>{rp(data.profit)}</strong></article></div><table className="profit-table monthly-profit"><tbody><tr className="section"><th>PENERIMAAN — {monthName(month).toUpperCase()}</th><td/></tr>{data.monthly.filter(e=>e.direction==="Masuk"&&e.category!=="Penawaran").map(e=><tr key={e.id}><td>{e.description}<small>{e.category} • {fmt(e.date)}</small></td><td>{rp(e.paidAmount)}</td></tr>)}<tr className="subtotal"><td>Total Penerimaan</td><td>{rp(data.revenue)}</td></tr><tr className="section"><th>PENGELUARAN</th><td/></tr>{data.monthly.filter(e=>e.direction==="Keluar").map(e=><tr key={e.id}><td>{e.description}<small>{e.category} • {fmt(e.date)}</small></td><td>({rp(e.paidAmount)})</td></tr>)}<tr className="subtotal"><td>Total Pengeluaran</td><td>({rp(data.expense)})</td></tr><tr className="grand"><td>LABA / (RUGI) BERJALAN</td><td>{rp(data.profit)}</td></tr></tbody></table></div>}
 <div className="balance-sign"><div><p>Disusun oleh,</p><br/><strong>Bagian Keuangan</strong></div><div><p>Batam, {fmt(today)}<br/>Disetujui oleh,</p><br/><strong>Andika Pratama, ST</strong><small>Direktur</small></div></div></section>;
}

