"use client";
import { useMemo, useState } from "react";
import { COST_COMPONENTS, SERVICE_CATALOG } from "./service-catalog";

type Project={id:number;code:string;name:string;serviceType?:string;clientName?:string;contractValue:number;budget:number;progress:number;status:string;startDate:string;endDate:string};
type Entry={projectId:number|null;direction:string;paidAmount:number};
const rp=(n:number)=>new Intl.NumberFormat("id-ID",{style:"currency",currency:"IDR",maximumFractionDigits:0}).format(n||0);
const shortRp=(n:number)=>n>=1e9?`Rp ${(n/1e9).toFixed(1)} M`:n>=1e6?`Rp ${(n/1e6).toFixed(0)} jt`:rp(n);
const 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 ProjectServices({projects,entries,onDelete,onEdit}:{projects:Project[];entries:Entry[];onDelete:(kind:"project",id:number,name:string)=>void;onEdit:(id:number,payload:Record<string,unknown>)=>Promise<boolean>}){
 const [view,setView]=useState<"active"|"catalog">("catalog"),[category,setCategory]=useState("Semua"),[query,setQuery]=useState(""),[selected,setSelected]=useState(0);
 const [editing,setEditing]=useState<Project|null>(null),[saving,setSaving]=useState(false),[editError,setEditError]=useState("");
 const categories=["Semua",...Array.from(new Set(SERVICE_CATALOG.map(x=>x.category)))];
 const filtered=useMemo(()=>SERVICE_CATALOG.filter(x=>(category==="Semua"||x.category===category)&&x.name.toLowerCase().includes(query.toLowerCase())),[category,query]);
 const service=SERVICE_CATALOG[selected];
 return <section className="project-services">
  <div className="project-hero"><div><span>KATALOG PROYEK TERINTEGRASI</span><h2>Layanan, tahapan, dan kendali biaya proyek</h2><p>Pilih layanan untuk melihat alur pengurusan, tim ahli, durasi, dan rentang estimasi fee.</p></div><div><strong>{SERVICE_CATALOG.length}</strong><small>jenis layanan</small></div></div>
  <div className="project-tabs"><button className={view==="catalog"?"active":""} onClick={()=>setView("catalog")}>Katalog Layanan & Biaya</button><button className={view==="active"?"active":""} onClick={()=>setView("active")}>Status Proyek <b>{projects.length}</b></button></div>
  {view==="active"?<div className="project-groups">{[["Sedang Berjalan",projects.filter(p=>p.status==="Berjalan"||p.status==="Perencanaan"||p.status==="Tertunda")],["Selesai",projects.filter(p=>p.status==="Selesai"||p.progress>=100)],["Berhenti / Tidak Dilanjutkan",projects.filter(p=>/berhenti|tidak dilanjutkan/i.test(p.status))]].map(([label,list])=><section key={label as string}><div className="group-heading"><h3>{label as string}</h3><span>{(list as Project[]).length} proyek</span></div><div className="cards-grid">{(list as Project[]).map((p,i)=>{const inc=entries.filter(e=>e.projectId===p.id&&e.direction==="Masuk").reduce((a,e)=>a+e.paidAmount,0),out=entries.filter(e=>e.projectId===p.id&&e.direction==="Keluar").reduce((a,e)=>a+e.paidAmount,0),paid=p.contractValue>0&&inc>=p.contractValue;return <article className="project-card" key={p.id}><div className="project-top"><span>{String(i+1).padStart(2,"0")} · {p.code}</span><em>{p.status}</em></div><h3>{p.name}</h3><p>{p.serviceType||"Layanan belum dipilih"} · {p.clientName||"Tanpa klien"}</p><div className="payment-state"><b className={paid?"paid":"unpaid"}>{paid?"Sudah Terbayar":"Belum Terbayar"}</b><span>{shortRp(inc)} / {shortRp(p.contractValue)}</span></div><div className="metric-row"><div><small>Nilai kontrak</small><strong>{shortRp(p.contractValue)}</strong></div><div><small>Laba kas</small><strong className={inc-out>=0?"positive":"negative"}>{shortRp(inc-out)}</strong></div></div><div className="progress"><i style={{width:`${p.progress}%`}}/></div><div className="project-foot"><span>Progres {p.progress}%</span><span>Target {fmt(p.endDate)}</span></div><div className="project-actions"><button className="edit-project" onClick={()=>{setEditing(p);setEditError("")}}>Edit Proyek</button><button className="delete-project" onClick={()=>onDelete("project",p.id,p.name)}>Hapus Proyek</button></div></article>})}{!(list as Project[]).length&&<div className="catalog-empty">Tidak ada proyek pada kelompok ini.</div>}</div></section>)}</div>:
  <><div className="catalog-tools"><div className="category-chips">{categories.map(c=><button key={c} className={category===c?"active":""} onClick={()=>setCategory(c)}>{c}</button>)}</div><input value={query} onChange={e=>setQuery(e.target.value)} placeholder="Cari AMDAL, Pertek, PKKPR…"/></div>
  <div className="catalog-layout"><div className="service-list">{filtered.map(item=>{const idx=SERVICE_CATALOG.indexOf(item);return <button key={item.name} className={selected===idx?"selected":""} onClick={()=>setSelected(idx)}><span>{item.category}</span><strong>{item.name}</strong><small>{item.duration} · {shortRp(item.feeLow)}–{shortRp(item.feeHigh)}</small></button>})}{!filtered.length&&<div className="catalog-empty">Layanan tidak ditemukan.</div>}</div>
  <article className="service-detail"><div className="service-detail-head"><div><span>{service.category}</span><h3>{service.name}</h3><p>{service.legal}</p></div><div><small>Estimasi fee jasa</small><strong>{shortRp(service.feeLow)}–{shortRp(service.feeHigh)}</strong><em>{service.duration}</em></div></div>
   <div className="service-grid"><div><h4>Tahapan pekerjaan & pengurusan</h4><ol>{service.stages.map((s,i)=><li key={s}><b>{i+1}</b><span>{s}</span></li>)}</ol></div><div><h4>Komposisi tenaga ahli</h4><p className="expert-box">{service.experts}</p><h4>Simulasi komponen biaya</h4><div className="cost-bars">{COST_COMPONENTS.map(([label,pct])=><div key={label}><span>{label}<b>{pct}%</b></span><i><em style={{width:`${pct}%`}}/></i><small>{rp(service.feeLow*pct/100)}–{rp(service.feeHigh*pct/100)}</small></div>)}</div></div></div>
  </article></div>
  <div className="estimate-note"><strong>Catatan estimasi.</strong> Rentang di atas adalah anggaran awal jasa konsultansi JLBB berbasis kompleksitas, kebutuhan personel, remunerasi minimal tenaga ahli Kementerian PU, dan Billing Rate INKINDO. Nilai final wajib mengikuti KAK, lokasi, volume survei, jenjang/masa kerja ahli, dan negosiasi. Belum termasuk PPN, PNBP/retribusi resmi, sampling/laboratorium khusus, perjalanan luar Batam, pengadaan alat, dan pekerjaan konstruksi kecuali dinyatakan dalam penawaran.</div>
  <div className="regulation-links"><h3>Dasar acuan utama</h3><div><a href="https://peraturan.bpk.go.id/Details/246523/uu-no-6-tahun-2023" target="_blank" rel="noreferrer">UU 6/2023 Cipta Kerja</a><a href="https://peraturan.bpk.go.id/Details/319773/pp-no-28-tahun-2025" target="_blank" rel="noreferrer">PP 28/2025 OSS-RBA</a><a href="https://peraturan.go.id/id/pp-no-22-tahun-2021" target="_blank" rel="noreferrer">PP 22/2021 PPLH</a><a href="https://jdih.pu.go.id/detail-dokumen/KepmenPU-nomor-33KPTSMM2025-tahun-2025-BESARAN-REMUNERASI-MINIMAL-TENAGA-KERJA-KONSTRUKSI-PADA-JENJANG-KUALIFIKASI-AHLI-UNTUK-LAYANAN-JASA-KONSULTANSI-KONSTRUKSI" target="_blank" rel="noreferrer">Kepmen PU 33/KPTS/M/2025</a><a href="https://www.inkindo.org/news/buku-billing-rate-inkindo-2026" target="_blank" rel="noreferrer">Billing Rate INKINDO 2026</a><a href="https://oss.go.id/id/panduan" target="_blank" rel="noreferrer">Panduan OSS</a></div></div></>}
 {editing&&<div className="modal-backdrop" onMouseDown={e=>e.target===e.currentTarget&&setEditing(null)}><form className="modal project-edit-modal" onSubmit={async e=>{e.preventDefault();setSaving(true);setEditError("");const ok=await onEdit(editing.id,Object.fromEntries(new FormData(e.currentTarget).entries()));setSaving(false);if(ok)setEditing(null);else setEditError("Perubahan belum dapat disimpan.")}}><div className="modal-head"><div><span>PERBARUI DATA PROYEK</span><h2>{editing.code}</h2></div><button type="button" onClick={()=>setEditing(null)}>×</button></div><div className="form-grid"><label className="wide"><span>Nama proyek</span><input name="name" defaultValue={editing.name} required/></label><label className="wide"><span>Jenis layanan</span><select name="serviceType" defaultValue={editing.serviceType||""}><option value="">— Pilih layanan —</option>{SERVICE_CATALOG.map(s=><option key={s.name}>{s.name}</option>)}</select></label><label><span>Nilai kontrak</span><input name="contractValue" type="number" defaultValue={editing.contractValue}/></label><label><span>Anggaran biaya</span><input name="budget" type="number" defaultValue={editing.budget}/></label><label><span>Progres (%)</span><input name="progress" type="number" min="0" max="100" defaultValue={editing.progress}/></label><label><span>Status</span><select name="status" defaultValue={editing.status}>{["Perencanaan","Berjalan","Tertunda","Selesai","Berhenti / Tidak Dilanjutkan"].map(s=><option key={s}>{s}</option>)}</select></label><label><span>Tanggal mulai</span><input name="startDate" type="date" defaultValue={editing.startDate}/></label><label><span>Target selesai</span><input name="endDate" type="date" defaultValue={editing.endDate}/></label></div>{editError&&<p className="form-error">{editError}</p>}<div className="modal-actions"><button type="button" onClick={()=>setEditing(null)}>Batal</button><button className="primary" disabled={saving}>{saving?"Menyimpan…":"Simpan Perubahan"}</button></div></form></div>}
 </section>;
}
