"use client";
import { useMemo,useState } from "react";
type Client={id:number;company:string;contact:string;phone:string;email:string};type Project={id:number;clientId:number|null};
type Entry={id:number;date:string;category:string;direction:string;description:string;amount:number;paidAmount:number;status:string;projectName?:string;clientName?:string};
const today=new Date().toISOString().slice(0,10),yearStart=`${new Date().getFullYear()}-01-01`,rp=(n:number)=>new Intl.NumberFormat("id-ID",{style:"currency",currency:"IDR",maximumFractionDigits:0}).format(n||0),fmt=(d:string)=>new Intl.DateTimeFormat("id-ID",{day:"2-digit",month:"short",year:"numeric"}).format(new Date(d+"T00:00:00"));
function Range({from,to,setFrom,setTo}:{from:string;to:string;setFrom:(v:string)=>void;setTo:(v:string)=>void}){return <div className="date-range"><label>Dari<input type="date" value={from} onChange={e=>setFrom(e.target.value)}/></label><span>—</span><label>Sampai<input type="date" value={to} onChange={e=>setTo(e.target.value)}/></label></div>}
export function CompactTransactions({entries,onDelete}:{entries:Entry[];onDelete:(id:number,name:string)=>void}){const[from,setFrom]=useState(yearStart),[to,setTo]=useState(today),rows=entries.filter(e=>e.date>=from&&e.date<=to&&!['Penawaran'].includes(e.category)),incoming=rows.filter(e=>e.direction==="Masuk"),outgoing=rows.filter(e=>e.direction==="Keluar");const Ledger=({title,list,tone}:{title:string;list:Entry[];tone:string})=><article className={`ledger-half ${tone}`}><div><h3>{title}</h3><strong>{rp(list.reduce((a,e)=>a+(e.paidAmount||e.amount),0))}</strong></div><table><thead><tr><th>Tanggal</th><th>Jenis transaksi</th><th>Jumlah</th><th/></tr></thead><tbody>{list.map((e,i)=><tr key={e.id}><td>{fmt(e.date)}</td><td>{i+1}. {e.category} — {e.description}</td><td>{rp(e.paidAmount||e.amount)}</td><td><button onClick={()=>onDelete(e.id,e.description)}>Hapus</button></td></tr>)}{!list.length&&<tr><td colSpan={4}>Tidak ada transaksi.</td></tr>}</tbody></table></article>;return <section className="panel page-panel compact-ledger"><div className="page-head"><div><h2>Rekap Transaksi</h2><p>Pemasukan dan pengeluaran dalam satu compile</p></div><Range from={from} to={to} setFrom={setFrom} setTo={setTo}/></div><div className="dual-ledger"><Ledger title="PEMASUKAN" list={incoming} tone="income-ledger"/><Ledger title="PENGELUARAN" list={outgoing} tone="expense-ledger"/></div><div className="ledger-net"><span>SELISIH BERSIH</span><strong className={incoming.reduce((a,e)=>a+(e.paidAmount||e.amount),0)-outgoing.reduce((a,e)=>a+(e.paidAmount||e.amount),0)>=0?"positive":"negative"}>{rp(incoming.reduce((a,e)=>a+(e.paidAmount||e.amount),0)-outgoing.reduce((a,e)=>a+(e.paidAmount||e.amount),0))}</strong></div></section>}
export function DebtReceivable({entries,onStatus}:{entries:Entry[];onStatus:(entry:Entry,status:string)=>void}){const[from,setFrom]=useState(yearStart),[to,setTo]=useState(today),rows=useMemo(()=>entries.filter(e=>e.date>=from&&e.date<=to&&["Piutang","Hutang","Tagihan","Invoice"].includes(e.category)),[entries,from,to]),receivable=rows.filter(e=>e.direction==="Masuk").reduce((a,e)=>a+Math.max(0,e.amount-e.paidAmount),0),payable=rows.filter(e=>e.direction==="Keluar").reduce((a,e)=>a+Math.max(0,e.amount-e.paidAmount),0);return <section className="panel page-panel"><div className="page-head"><div><h2>Hutang & Piutang</h2><p>Tahapan Draft, Revisi, dan Telah Dibayarkan tersimpan dalam database</p></div><Range from={from} to={to} setFrom={setFrom} setTo={setTo}/></div><div className="debt-totals"><article><span>TOTAL PIUTANG</span><strong>{rp(receivable)}</strong><small>Belum diterima</small></article><article><span>TOTAL HUTANG</span><strong>{rp(payable)}</strong><small>Belum dibayar</small></article><article><span>SELISIH BERSIH</span><strong className={receivable-payable>=0?"positive":"negative"}>{rp(receivable-payable)}</strong><small>Piutang dikurangi hutang</small></article></div><div className="table-wrap"><table><thead><tr><th>Tanggal</th><th>Jenis</th><th>Klien/Proyek</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>{e.category}</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><select className="status-select" 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></td></tr>)}</tbody></table></div></section>}
export function ClientDirectory({items,projects,onDelete}:{items:Client[];projects:Project[];onDelete:(kind:"client",id:number,name:string)=>void}){return <section className="panel page-panel"><div className="page-head"><div><h2>Database Klien & Perusahaan</h2><p>Nomor urut otomatis dan rekaman relasi proyek</p></div><span className="count-chip">{items.length} perusahaan</span></div><div className="client-grid numbered-clients">{items.map((c,i)=><article key={c.id}><span className="row-number">{String(i+1).padStart(2,"0")}</span><div className="avatar">{c.company.replace("PT.","").trim().slice(0,2).toUpperCase()}</div><div><h3>{c.company}</h3><p>{c.contact||"Kontak belum diisi"}</p><small>{c.phone||"—"} • {c.email||"—"}</small><span>{projects.filter(p=>p.clientId===c.id).length} proyek tercatat</span></div><button className="delete-btn" onClick={()=>onDelete("client",c.id,c.company)}>Hapus</button></article>)}</div></section>}
type Approval={reportType:string;period:string;status:string;approvedBy:string;approvedAt:string};
export function StandardProfitReport({entries,projects,approvals,role,onApprove}:{entries:Entry[];projects:{id:number;name:string;contractValue:number;progress:number}[];approvals:Approval[];role:"director"|"manager";onApprove:(type:"Laba Rugi",period:string)=>void}){
 const[selectedMonth,setSelectedMonth]=useState(today.slice(0,7)),year=selectedMonth.slice(0,4),monthRows=entries.filter(e=>e.date.startsWith(selectedMonth)),revenueRows=monthRows.filter(e=>e.direction==="Masuk"&&e.category!=="Penawaran"),expenseRows=monthRows.filter(e=>e.direction==="Keluar"),serviceRevenue=revenueRows.filter(e=>["Penerimaan","Invoice"].includes(e.category)).reduce((a,e)=>a+e.paidAmount,0),otherRevenue=revenueRows.filter(e=>!["Penerimaan","Invoice"].includes(e.category)).reduce((a,e)=>a+e.paidAmount,0),projectExpense=expenseRows.filter(e=>e.category==="Pengeluaran").reduce((a,e)=>a+e.paidAmount,0),otherExpense=expenseRows.filter(e=>e.category!=="Pengeluaran").reduce((a,e)=>a+e.paidAmount,0),revenue=serviceRevenue+otherRevenue,expense=projectExpense+otherExpense,profit=revenue-expense,monthTitle=new Intl.DateTimeFormat("id-ID",{month:"long",year:"numeric"}).format(new Date(`${selectedMonth}-01T00:00:00`));
 const annual=Array.from({length:12},(_,index)=>{const key=`${year}-${String(index+1).padStart(2,"0")}`,rows=entries.filter(e=>e.date.startsWith(key)),income=rows.filter(e=>e.direction==="Masuk"&&e.category!=="Penawaran").reduce((a,e)=>a+e.paidAmount,0),cost=rows.filter(e=>e.direction==="Keluar").reduce((a,e)=>a+e.paidAmount,0);return{key,label:new Intl.DateTimeFormat("id-ID",{month:"long"}).format(new Date(`${key}-01T00:00:00`)),income,cost,profit:income-cost}}),annualIncome=annual.reduce((s,m)=>s+m.income,0),annualExpense=annual.reduce((s,m)=>s+m.cost,0),approval=approvals.find(a=>a.reportType==="Laba Rugi"&&a.period===selectedMonth);
 return <section className="report-sheet standard-report monthly-profit-report"><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="report-heading"><div><span>Laporan Keuangan Bulanan</span><h1>Laporan Laba Rugi</h1><p>Untuk periode {monthTitle}</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="monthly-report-controls"><label>Periode Bulan<input type="month" value={selectedMonth} onChange={e=>setSelectedMonth(e.target.value)}/></label>{role==="director"&&!approval&&<button className="approve-button" onClick={()=>onApprove("Laba Rugi",selectedMonth)}>✓ Setujui Laporan</button>}<button onClick={()=>window.print()}>⇩ Cetak / PDF</button></div></div><div className="report-meta"><span>Basis pencatatan: transaksi kas terealisasi</span><span>Tanggal cetak: {fmt(today)}</span></div><table className="profit-table"><tbody><tr className="section"><th>Pendapatan</th><td/></tr><tr><td>Pendapatan jasa dan proyek</td><td>{rp(serviceRevenue)}</td></tr><tr><td>Pendapatan lain-lain</td><td>{rp(otherRevenue)}</td></tr><tr className="subtotal"><td>Total Pendapatan</td><td>{rp(revenue)}</td></tr><tr className="section"><th>Beban</th><td/></tr><tr><td>Beban proyek dan operasional</td><td>({rp(projectExpense)})</td></tr><tr><td>Beban lain-lain dan pembayaran kewajiban</td><td>({rp(otherExpense)})</td></tr><tr className="subtotal"><td>Total Beban</td><td>({rp(expense)})</td></tr><tr className="grand"><td>Laba / (Rugi) Bersih</td><td className={profit>=0?"positive":"negative"}>{rp(profit)}</td></tr></tbody></table><section className="annual-compile"><div><h3>Rekap Laba Rugi Bulanan Tahun {year}</h3><p>Kompilasi otomatis dari transaksi setiap bulan.</p></div><div className="table-wrap"><table><thead><tr><th>Bulan</th><th>Pendapatan</th><th>Beban</th><th>Laba / (Rugi)</th><th>Margin</th></tr></thead><tbody>{annual.map(m=><tr key={m.key} className={m.key===selectedMonth?"selected-month":""}><td>{m.label}</td><td>{rp(m.income)}</td><td>{rp(m.cost)}</td><td className={m.profit>=0?"positive":"negative"}>{rp(m.profit)}</td><td>{m.income?(m.profit/m.income*100).toFixed(1):"0.0"}%</td></tr>)}</tbody><tfoot><tr><th>Total Tahun {year}</th><th>{rp(annualIncome)}</th><th>{rp(annualExpense)}</th><th className={annualIncome-annualExpense>=0?"positive":"negative"}>{rp(annualIncome-annualExpense)}</th><th>{annualIncome?((annualIncome-annualExpense)/annualIncome*100).toFixed(1):"0.0"}%</th></tr></tfoot></table></div></section><div className="report-projects"><h3>Lampiran Ringkas Proyek</h3>{projects.map((p,i)=><div key={p.id}><span>{i+1}. {p.name}</span><span>{p.progress}%</span><span>{rp(p.contractValue)}</span></div>)}</div><div className="signature"><div><p>Disusun oleh,</p><br/><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>
}

