"use client";
import { useEffect,useMemo,useState } from "react";
import { COST_COMPONENTS,SERVICE_CATALOG } from "./service-catalog";
type Client={id:number;company:string;address:string};type Project={id:number;name:string;serviceType?:string;clientId:number|null};
type Item={description:string;qty:number;unit:string;price:number};
type Doc={id:number;type:string;documentNo:string;date:string;dueDate:string;clientId:number;clientName?:string;clientAddress?:string;projectName?:string;subject:string;itemsJson:string;taxMode:string;taxRate:number;discountType:string;discountValue:number;subtotal:number;discountAmount:number;taxAmount:number;total:number;paidAmount:number;status:string;sourceDocumentId:number|null;sentAt:string;sentTo:string;paymentDate:string;paymentMethod:string;terms:string;notes:string};
const rp=(n:number)=>new Intl.NumberFormat("id-ID",{style:"currency",currency:"IDR",maximumFractionDigits:0}).format(n||0),today=new Date().toISOString().slice(0,10),fmt=(d:string)=>d?new Intl.DateTimeFormat("id-ID",{day:"2-digit",month:"long",year:"numeric"}).format(new Date(d+"T00:00:00")):"—";
export default function DocumentBuilder({mode,clients,projects}:{mode:"Penawaran"|"Tagihan";clients:Client[];projects:Project[]}){
 const[docs,setDocs]=useState<Doc[]>([]),[show,setShow]=useState(false),[selected,setSelected]=useState<Doc|null>(null),[saving,setSaving]=useState(false),[message,setMessage]=useState(""),[items,setItems]=useState<Item[]>([{description:"Jasa konsultansi lingkungan",qty:1,unit:"Paket",price:0}]);
 const[serviceName,setServiceName]=useState(""),[feeLevel,setFeeLevel]=useState<"low"|"recommended"|"high">("recommended"),[sendDoc,setSendDoc]=useState<Doc|null>(null),[receiptDoc,setReceiptDoc]=useState<Doc|null>(null),[workflowDoc,setWorkflowDoc]=useState<Doc|null>(null),[workflowStatus,setWorkflowStatus]=useState("Draft"),[sentAt,setSentAt]=useState(today),[sentTo,setSentTo]=useState(""),[paymentDate,setPaymentDate]=useState(today),[paymentMethod,setPaymentMethod]=useState("Transfer Bank");
 const[form,setForm]=useState({date:today,dueDate:"",clientId:"",projectId:"",subject:"",taxMode:"exclude",taxRate:"11",discountType:"percent",discountValue:"0",status:mode==="Penawaran"?"Draft":"Belum Terkirim",sentAt:"",sentTo:"",terms:"",notes:""});
 const load=async()=>{const r=await fetch("/api/documents",{cache:"no-store"}),j=await r.json();setDocs(j.documents||[])};useEffect(()=>{void load();const open=()=>setShow(true);window.addEventListener("open-document-builder",open);return()=>window.removeEventListener("open-document-builder",open)},[]);
 const calc=useMemo(()=>{const subtotal=items.reduce((a,x)=>a+(Number(x.qty)||0)*(Number(x.price)||0),0),dv=Number(form.discountValue)||0,discount=form.discountType==="percent"?subtotal*dv/100:Math.min(subtotal,dv),after=Math.max(0,subtotal-discount),rate=Number(form.taxRate)||0,tax=form.taxMode==="exclude"?after*rate/100:form.taxMode==="include"?after*rate/(100+rate):0,total=form.taxMode==="exclude"?after+tax:after;return{subtotal,discount,tax,total}},[items,form]);
 const change=(k:string,v:string)=>setForm(x=>({...x,[k]:v}));
 const applyTemplate=(name:string,level:"low"|"recommended"|"high"="recommended")=>{const s=SERVICE_CATALOG.find(x=>x.name===name);if(!s)return;const target=level==="low"?s.feeLow:level==="high"?s.feeHigh:(s.feeLow+s.feeHigh)/2,round=(n:number)=>Math.round(n/500_000)*500_000;setServiceName(name);setFeeLevel(level);setItems(COST_COMPONENTS.map(([label,pct])=>({description:`${label} — ${s.name}`,qty:1,unit:"Paket",price:round(target*pct/100)})));setForm(x=>({...x,subject:s.name,terms:"Pembayaran 30% setelah SPK, 40% setelah penyampaian draft, dan 30% setelah dokumen final/persetujuan sesuai ruang lingkup.",notes:`Durasi indikatif ${s.duration}. Acuan: ${s.legal}. Belum termasuk PPN, PNBP/retribusi resmi, pengujian khusus di luar lingkup, dan perjalanan di luar Batam.`}))};
 const chooseProject=(id:string)=>{change("projectId",id);const p=projects.find(x=>x.id===Number(id));if(mode==="Penawaran"&&p?.serviceType)applyTemplate(p.serviceType)};
 const save=async()=>{setSaving(true);setMessage("");const r=await fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind:"document",type:mode,...form,items})}),j=await r.json();setSaving(false);if(!r.ok){setMessage(j.error||"Gagal menyimpan");return}setMessage(`${mode} ${j.documentNo} berhasil disimpan.`);setShow(false);await load()};
 const markSent=async()=>{if(!sendDoc||!sentTo)return;setSaving(true);const r=await fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind:"update_status",id:sendDoc.id,status:"Terkirim",sentAt,sentTo})}),j=await r.json();setSaving(false);if(!r.ok){setMessage(j.error||"Gagal memperbarui status");return}setSendDoc(null);setSelected({...sendDoc,...j});setMessage(`Tagihan tercatat terkirim kepada ${sentTo}.`);await load()};
 const updateWorkflow=async()=>{if(!workflowDoc)return;setSaving(true);const r=await fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind:"update_status",id:workflowDoc.id,status:workflowStatus})}),j=await r.json();setSaving(false);if(!r.ok){setMessage(j.error||"Gagal memperbarui status");return}setWorkflowDoc(null);setSelected({...workflowDoc,...j});setMessage(`Tahapan penawaran diperbarui menjadi ${workflowStatus}.`);await load()};
 const makeReceipt=async()=>{if(!receiptDoc)return;setSaving(true);const r=await fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind:"receipt",sourceDocumentId:receiptDoc.id,paidAmount:receiptDoc.total,paymentDate,paymentMethod})}),j=await r.json();setSaving(false);if(!r.ok){setMessage(j.error||"Gagal membuat kwitansi");return}setReceiptDoc(null);await load();setSelected({...j,clientName:receiptDoc.clientName,clientAddress:receiptDoc.clientAddress,projectName:receiptDoc.projectName});setMessage(`Kwitansi ${j.documentNo} tercatat lunas.`)};
 const deleteDocument=async(doc:Doc)=>{if(!window.confirm(`Hapus ${doc.type} ${doc.documentNo}? Rekap transaksi terkait juga akan disesuaikan.`))return;setSaving(true);const r=await fetch(`/api/documents?id=${doc.id}`,{method:"DELETE"}),j=await r.json();setSaving(false);if(!r.ok){setMessage(j.error||"Gagal menghapus dokumen");return}if(selected?.id===doc.id)setSelected(null);setMessage(`${doc.type} ${doc.documentNo} berhasil dihapus.`);await load()};
 const list=docs.filter(d=>mode==="Penawaran"?d.type==="Penawaran":["Tagihan","Kwitansi"].includes(d.type));
 return <section className="document-workspace"><div className="doc-hero"><div><span>COMMERCIAL DOCUMENT HUB</span><h2>{mode==="Penawaran"?"Buat Penawaran Profesional":"Tagihan & Kwitansi Terintegrasi"}</h2><p>Nomor dokumen tersusun otomatis dan seluruh status tersimpan dalam database.</p></div><button className="primary" onClick={()=>setShow(true)}>＋ Buat {mode}</button></div>{message&&<div className="doc-message">{message}</div>}
 <div className="doc-grid"><article className="panel doc-list"><div className="panel-head"><div><h3>Arsip {mode}</h3><p>{list.length} dokumen tersimpan</p></div></div>{list.map((d,i)=><div className={`doc-archive-row ${selected?.id===d.id?"selected":""}`} key={d.id}><button className="doc-open" onClick={()=>setSelected(d)}><span className={`doc-type ${d.type.toLowerCase()}`}>{String(i+1).padStart(2,"0")}</span><div><strong>{d.documentNo}</strong><small>{d.clientName||"Klien"} • {fmt(d.date)}</small></div><div><b>{rp(d.total)}</b><em>{d.status}</em></div></button><button className="doc-delete" disabled={saving} onClick={()=>deleteDocument(d)}>Hapus</button></div>)}{!list.length&&<div className="doc-empty">Belum ada dokumen.</div>}</article>
 <article className="panel doc-preview">{selected?<>{mode==="Penawaran"&&<div className="workflow-toolbar"><span>Tahapan: <b>{selected.status}</b></span><button onClick={()=>{setWorkflowDoc(selected);setWorkflowStatus(selected.status)}}>↻ Ubah Tahapan</button></div>}<DocumentPrint doc={selected} saving={saving} onReceipt={mode==="Tagihan"&&selected.type==="Tagihan"?()=>{setReceiptDoc(selected);setPaymentDate(today)}:undefined} onSend={mode==="Tagihan"&&selected.type==="Tagihan"&&selected.status!=="Terkirim"?()=>{setSendDoc(selected);setSentAt(today);setSentTo(selected.clientName||"")}:undefined}/></>:<div className="preview-empty"><span>▤</span><h3>Pilih dokumen</h3><p>Pratinjau siap cetak akan tampil di sini.</p></div>}</article></div>
 {show&&<div className="modal-backdrop"><div className="modal builder-modal"><div className="modal-head"><div><span>JLBB DOCUMENT COMPOSER</span><h2>{mode==="Penawaran"?"Penawaran Harga":"Tagihan / Invoice"}</h2></div><button onClick={()=>setShow(false)}>×</button></div><div className="builder-body"><div className="form-grid"><label><span>Nomor dokumen</span><input value="Otomatis saat disimpan" disabled/></label><Field label="Tanggal" type="date" value={form.date} onChange={v=>change("date",v)}/><label><span>Klien *</span><select value={form.clientId} onChange={e=>change("clientId",e.target.value)}><option value="">— Pilih klien —</option>{clients.map(c=><option key={c.id} value={c.id}>{c.company}</option>)}</select></label><label><span>Proyek</span><select value={form.projectId} onChange={e=>chooseProject(e.target.value)}><option value="">— Umum —</option>{projects.filter(p=>!form.clientId||p.clientId===Number(form.clientId)).map(p=><option key={p.id} value={p.id}>{p.name}</option>)}</select></label><Field wide label="Perihal / pekerjaan" value={form.subject} onChange={v=>change("subject",v)}/>{mode==="Penawaran"?<label><span>Status Penawaran</span><select value={form.status} onChange={e=>change("status",e.target.value)}><option>Draft</option><option>Submit</option><option>Revisi</option></select></label>:<><Field label="Jatuh tempo" type="date" value={form.dueDate} onChange={v=>change("dueDate",v)}/><label><span>Status Pengiriman</span><select value={form.status} onChange={e=>change("status",e.target.value)}><option>Belum Terkirim</option><option>Terkirim</option></select></label>{form.status==="Terkirim"&&<><Field label="Tanggal terkirim" type="date" value={form.sentAt} onChange={v=>change("sentAt",v)}/><Field label="Dikirim kepada" value={form.sentTo} onChange={v=>change("sentTo",v)}/></>}</>}</div>
 {mode==="Penawaran"&&<div className="estimate-template"><div className="template-title"><div><span>TEMPLATE ESTIMASI BIAYA PROYEK</span><h3>Pilih jenis layanan untuk mengisi rincian otomatis</h3></div>{serviceName&&<b>{SERVICE_CATALOG.find(x=>x.name===serviceName)?.duration}</b>}</div><div className="template-controls"><label><span>Jenis proyek / layanan</span><select value={serviceName} onChange={e=>applyTemplate(e.target.value)}><option value="">— Pilih template layanan —</option>{SERVICE_CATALOG.map(s=><option key={s.name} value={s.name}>{s.category} — {s.name}</option>)}</select></label><div><span>Skenario estimasi</span><div className="fee-scenarios">{(["low","recommended","high"] as const).map(level=><button key={level} disabled={!serviceName} className={feeLevel===level?"active":""} onClick={()=>applyTemplate(serviceName,level)}>{level==="low"?"Minimum":level==="high"?"Maksimum":"Rekomendasi"}</button>)}</div></div></div>{serviceName&&(()=>{const s=SERVICE_CATALOG.find(x=>x.name===serviceName)!;return <div className="template-summary"><p><small>Rentang katalog</small><strong>{rp(s.feeLow)} – {rp(s.feeHigh)}</strong></p><p><small>Nilai template</small><strong>{rp(calc.subtotal)}</strong></p><p><small>Tenaga ahli</small><strong>{s.experts}</strong></p></div>})()}</div>}
 <div className="items-title"><h3>Rincian Pekerjaan</h3><button onClick={()=>setItems(x=>[...x,{description:"",qty:1,unit:"Paket",price:0}])}>＋ Tambah baris</button></div><div className="item-table"><div className="item-head"><span>Deskripsi</span><span>Qty</span><span>Satuan</span><span>Harga</span><span/></div>{items.map((it,i)=><div className="item-row" key={i}><textarea rows={2} value={it.description} onChange={e=>setItems(x=>x.map((v,j)=>j===i?{...v,description:e.target.value}:v))}/><input type="number" value={it.qty} onChange={e=>setItems(x=>x.map((v,j)=>j===i?{...v,qty:Number(e.target.value)}:v))}/><input value={it.unit} onChange={e=>setItems(x=>x.map((v,j)=>j===i?{...v,unit:e.target.value}:v))}/><input type="number" value={it.price} onChange={e=>setItems(x=>x.map((v,j)=>j===i?{...v,price:Number(e.target.value)}:v))}/><button disabled={items.length===1} onClick={()=>setItems(x=>x.filter((_,j)=>j!==i))}>×</button></div>)}</div>
 <div className="calc-area"><div className="tax-options"><label><span>Perlakuan Pajak</span><select value={form.taxMode} onChange={e=>change("taxMode",e.target.value)}><option value="exclude">Exclude Tax</option><option value="include">Include Tax</option><option value="none">Non-Pajak</option></select></label><Field label="Tarif pajak (%)" type="number" value={form.taxRate} onChange={v=>change("taxRate",v)}/><label><span>Jenis diskon</span><select value={form.discountType} onChange={e=>change("discountType",e.target.value)}><option value="percent">Persentase (%)</option><option value="nominal">Nominal (Rp)</option></select></label><Field label="Nilai diskon" type="number" value={form.discountValue} onChange={v=>change("discountValue",v)}/></div><div className="live-total"><p><span>Subtotal</span><b>{rp(calc.subtotal)}</b></p><p><span>Diskon</span><b>- {rp(calc.discount)}</b></p><p><span>Pajak</span><b>{rp(calc.tax)}</b></p><p className="grand"><span>TOTAL</span><b>{rp(calc.total)}</b></p></div></div><div className="form-grid notes"><Field wide multiline label="Syarat pembayaran" value={form.terms} onChange={v=>change("terms",v)}/><Field wide multiline label="Catatan" value={form.notes} onChange={v=>change("notes",v)}/></div></div><div className="modal-actions"><button onClick={()=>setShow(false)}>Batal</button><button className="primary" disabled={saving} onClick={save}>{saving?"Menyimpan…":`Simpan ${mode}`}</button></div></div></div>}
 {sendDoc&&<div className="modal-backdrop"><div className="modal action-modal"><div className="modal-head"><div><span>STATUS PENGIRIMAN</span><h2>Catat Tagihan Terkirim</h2></div><button onClick={()=>setSendDoc(null)}>×</button></div><div className="form-grid"><Field label="Tanggal terkirim" type="date" value={sentAt} onChange={setSentAt}/><Field label="Dikirim kepada" value={sentTo} onChange={setSentTo}/></div><div className="modal-actions"><button onClick={()=>setSendDoc(null)}>Batal</button><button className="primary" disabled={saving||!sentTo} onClick={markSent}>Simpan Status</button></div></div></div>}
 {receiptDoc&&<div className="modal-backdrop"><div className="modal action-modal"><div className="modal-head"><div><span>KONFIRMASI PEMBAYARAN</span><h2>Buat Receipt / Kwitansi</h2></div><button onClick={()=>setReceiptDoc(null)}>×</button></div><div className="form-grid"><Field label="Tanggal dibayar" type="date" value={paymentDate} onChange={setPaymentDate}/><label><span>Cara pembayaran</span><select value={paymentMethod} onChange={e=>setPaymentMethod(e.target.value)}><option>Transfer Bank</option><option>Tunai</option><option>Giro</option><option>Cek</option><option>Virtual Account</option><option>Lainnya</option></select></label></div><div className="payment-confirm"><span>Jumlah pembayaran</span><strong>{rp(receiptDoc.total)}</strong></div><div className="modal-actions"><button onClick={()=>setReceiptDoc(null)}>Batal</button><button className="primary" disabled={saving} onClick={makeReceipt}>Terbitkan Kwitansi</button></div></div></div>}
 {workflowDoc&&<div className="modal-backdrop"><div className="modal action-modal"><div className="modal-head"><div><span>TAHAPAN PENAWARAN</span><h2>Ubah Status Dokumen</h2></div><button onClick={()=>setWorkflowDoc(null)}>×</button></div><div className="form-grid"><label className="wide"><span>Tahapan saat ini</span><select value={workflowStatus} onChange={e=>setWorkflowStatus(e.target.value)}><option>Draft</option><option>Revisi</option><option>Disetujui</option></select></label></div><div className="workflow-line"><i className={workflowStatus!=="Draft"?"done":"active"}>1</i><span>Draft</span><i className={workflowStatus==="Disetujui"?"done":workflowStatus==="Revisi"?"active":""}>2</i><span>Revisi</span><i className={workflowStatus==="Disetujui"?"active":""}>3</i><span>Disetujui</span></div><div className="modal-actions"><button onClick={()=>setWorkflowDoc(null)}>Batal</button><button className="primary" disabled={saving} onClick={updateWorkflow}>Simpan Tahapan</button></div></div></div>}
 </section>;
}
function DocumentPrint({doc,onReceipt,onSend,saving}:{doc:Doc;onReceipt?:()=>void;onSend?:()=>void;saving:boolean}){const items=JSON.parse(doc.itemsJson||"[]") as Item[];return <div className="print-doc"><div className="doc-toolbar"><span>Pratinjau {doc.type}</span><div>{onSend&&<button onClick={onSend}>✉ Tandai Terkirim</button>}{onReceipt&&<button onClick={onReceipt} disabled={saving}>✓ Catat Pembayaran & Kwitansi</button>}<button onClick={()=>window.print()}>⇩ Cetak / PDF</button></div></div><div className="doc-paper standard-finance-doc"><div className="doc-letterhead"><img src="/logo.png" alt="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="doc-title"><h1>{doc.type.toUpperCase()}</h1><strong>{doc.documentNo}</strong></div><div className="doc-parties"><div><small>Kepada Yth.</small><strong>{doc.clientName}</strong><span>{doc.clientAddress||"Alamat klien belum diisi"}</span></div><div><p><span>Tanggal</span><b>{fmt(doc.date)}</b></p>{doc.dueDate&&<p><span>Jatuh tempo</span><b>{fmt(doc.dueDate)}</b></p>}<p><span>Status</span><b>{doc.status}</b></p>{doc.sentAt&&<p><span>Terkirim</span><b>{fmt(doc.sentAt)} · {doc.sentTo}</b></p>}{doc.paymentDate&&<p><span>Dibayar</span><b>{fmt(doc.paymentDate)} · {doc.paymentMethod}</b></p>}</div></div><h3 className="doc-subject">Perihal: {doc.subject}</h3>{doc.type==="Kwitansi"?<div className="receipt-box"><small>SUDAH TERIMA DARI</small><strong>{doc.clientName}</strong><small>UANG SEJUMLAH</small><strong className="amount">{rp(doc.total)}</strong><p>Untuk pembayaran: {doc.subject}</p><p><b>Tanggal pembayaran:</b> {fmt(doc.paymentDate)} · <b>Metode:</b> {doc.paymentMethod}</p></div>:<table className="doc-items"><thead><tr><th>No.</th><th>Uraian</th><th>Qty</th><th>Harga Satuan</th><th>Jumlah</th></tr></thead><tbody>{items.map((x,i)=><tr key={i}><td>{i+1}</td><td>{x.description}<small>{x.unit}</small></td><td>{x.qty}</td><td>{rp(x.price)}</td><td>{rp(x.qty*x.price)}</td></tr>)}</tbody></table>}<div className="doc-totals"><p><span>Subtotal</span><b>{rp(doc.subtotal)}</b></p>{doc.discountAmount>0&&<p><span>Diskon</span><b>- {rp(doc.discountAmount)}</b></p>}<p><span>Pajak {doc.taxMode==="include"?"(include)":doc.taxMode==="exclude"?`${doc.taxRate}% (exclude)`:"(non-pajak)"}</span><b>{rp(doc.taxAmount)}</b></p><p><span>TOTAL</span><b>{rp(doc.total)}</b></p></div>{doc.terms&&<div className="doc-terms"><strong>Syarat Pembayaran</strong><p>{doc.terms}</p></div>}<div className="doc-sign"><div><p>Hormat kami,</p><br/><br/><strong>PT. Jasa Lingkungan Bahari Batam</strong></div><div><p>Batam, {fmt(doc.date)}</p><br/><br/><strong>Andika Pratama, ST</strong><small>Direktur</small></div></div></div></div>}
function Field({label,value,onChange,type="text",wide=false,multiline=false}:{label:string;value:string;onChange:(v:string)=>void;type?:string;wide?:boolean;multiline?:boolean}){return <label className={wide?"wide":""}><span>{label}</span>{multiline?<textarea rows={3} value={value} onChange={e=>onChange(e.target.value)}/>:<input type={type} value={value} onChange={e=>onChange(e.target.value)}/>}</label>}
