/* global React, Icon, fmtRp */
const { useState: useStateFA, useEffect: useEffectFA } = React;

function FixedAssetsPage() {
  const [data, setData] = useStateFA(null);
  const [createOpen, setCreateOpen] = useStateFA(false);
  const [busy, setBusy] = useStateFA(false);
  const [result, setResult] = useStateFA(null);

  const load = async () => {
    const r = await window.Api.get('/api/fixed-assets');
    setData(r.data);
  };
  useEffectFA(() => { load(); }, []);

  const runDepreciation = async () => {
    if (!confirm('Jalankan depresiasi bulan ini? Akan post jurnal otomatis.')) return;
    setBusy(true);
    setResult(null);
    try {
      const r = await window.Api.post('/api/fixed-assets/run-depreciation', {});
      setResult(r.data);
      await load();
    } catch (e) {
      alert('Gagal: ' + e.message);
    } finally { setBusy(false); }
  };

  if (!data) return <div className="page"><div className="card" style={{ padding:24, textAlign:'center', color:'var(--ink-500)' }}>Memuat…</div></div>;

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Aset Tetap</h1>
          <p className="page-sub">Daftar peralatan, kendaraan, perabot — dengan depresiasi straight-line otomatis</p>
        </div>
        <div className="page-actions">
          <button className="btn btn-secondary" onClick={runDepreciation} disabled={busy}>
            {busy ? 'Memproses…' : 'Jalankan Depresiasi Bulan Ini'}
          </button>
          <button className="btn btn-primary" onClick={() => setCreateOpen(true)}><Icon.plus/> Aset Baru</button>
        </div>
      </div>

      {result && (
        <div className="card" style={{ marginBottom:18, padding:'14px 18px', background:'var(--green-bg)', color:'var(--green)', fontSize:13 }}>
          ✓ {result.skipped ? result.message : (
            <>Depresiasi posted: <strong>{result.entry?.id}</strong> · {result.count} aset · Total Rp {result.totalAmount?.toLocaleString('id-ID')}</>
          )}
        </div>
      )}

      <div className="grid-4" style={{ marginBottom:18 }}>
        <FAStat label="Total Aset" value={data.assets.length}/>
        <FAStat label="Nilai Perolehan" value={fmtRp(data.totalAcquire)} tone="brand"/>
        <FAStat label="Akum. Penyusutan" value={fmtRp(data.totalAccum)} tone="rose"/>
        <FAStat label="Nilai Buku" value={fmtRp(data.totalBook)} tone="green"/>
      </div>

      <div className="card" style={{ padding:'12px 18px', marginBottom:14, fontSize:13, color:'var(--ink-700)', background:'var(--brand-50)' }}>
        💡 Depresiasi bulanan total kalau dijalankan: <strong>{fmtRp(data.monthlyDepreciationTotal)}</strong>
      </div>

      <div className="card" style={{ overflow:'hidden' }}>
        <table className="table">
          <thead>
            <tr>
              <th>Kode</th>
              <th>Nama</th>
              <th>Kategori</th>
              <th>Tgl Perolehan</th>
              <th style={{ textAlign:'right' }}>Harga Perolehan</th>
              <th style={{ textAlign:'right' }}>Penyusutan/bln</th>
              <th style={{ textAlign:'right' }}>Akum. Penyusutan</th>
              <th style={{ textAlign:'right' }}>Nilai Buku</th>
              <th>Sisa</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {data.assets.length === 0 && (
              <tr><td colSpan="10" style={{ padding:40, textAlign:'center', color:'var(--ink-500)' }}>
                Belum ada aset tetap. Klik <strong>Aset Baru</strong> untuk daftar peralatan/kendaraan.
              </td></tr>
            )}
            {data.assets.map(a => (
              <tr key={a.id}>
                <td><span className="mono" style={{ fontWeight:700 }}>{a.code}</span></td>
                <td>{a.name}</td>
                <td>{a.category && <span className="chip">{a.category}</span>}</td>
                <td style={{ fontSize:13 }}>{a.acquireDate}</td>
                <td style={{ textAlign:'right', fontWeight:600 }}>{fmtRp(Number(a.acquireCost))}</td>
                <td style={{ textAlign:'right', fontSize:13 }}>{fmtRp(Number(a.monthlyDepreciation))}</td>
                <td style={{ textAlign:'right', color:'var(--rose)' }}>{fmtRp(Number(a.accumulatedDepreciation))}</td>
                <td style={{ textAlign:'right', fontWeight:700, color: a.bookValue <= 0 ? 'var(--ink-400)' : 'var(--brand-600)' }}>
                  {fmtRp(a.bookValue)}
                </td>
                <td style={{ fontSize:12 }}>{a.monthsRemaining} / {a.usefulLifeMonths} bln</td>
                <td>
                  {a.status === 'active'
                    ? <span className="chip chip-green"><span className="chip-dot"/>Aktif</span>
                    : <span className="chip"><span className="chip-dot"/>Disposed</span>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {createOpen && <NewFixedAssetModal onClose={() => setCreateOpen(false)} onCreated={load}/>}
    </div>
  );
}

function NewFixedAssetModal({ onClose, onCreated }) {
  const [code, setCode] = useStateFA('');
  const [name, setName] = useStateFA('');
  const [category, setCategory] = useStateFA('');
  const [acquireDate, setAcquireDate] = useStateFA(new Date().toISOString().slice(0,10));
  const [acquireCost, setAcquireCost] = useStateFA('');
  const [salvageValue, setSalvageValue] = useStateFA('0');
  const [usefulLifeMonths, setUsefulLifeMonths] = useStateFA('60');
  const [assetAccountCode, setAssetAccountCode] = useStateFA('1210');
  const [accumDepAccountCode, setAccumDepAccountCode] = useStateFA('1220');
  const [depExpenseAccountCode, setDepExpenseAccountCode] = useStateFA('5200');
  const [busy, setBusy] = useStateFA(false);
  const [error, setError] = useStateFA('');

  const cost = Number(acquireCost) || 0;
  const salvage = Number(salvageValue) || 0;
  const months = Number(usefulLifeMonths) || 1;
  const monthly = months > 0 ? (cost - salvage) / months : 0;

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    setBusy(true);
    try {
      await window.Api.post('/api/fixed-assets', {
        code, name, category: category || undefined,
        acquireDate,
        acquireCost: cost,
        salvageValue: salvage,
        usefulLifeMonths: months,
        assetAccountCode, accumDepAccountCode, depExpenseAccountCode,
      });
      await onCreated();
      onClose();
    } catch (err) {
      setError(err.body?.message || err.message || 'Gagal');
      setBusy(false);
    }
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{ maxWidth:620 }} onClick={e=>e.stopPropagation()}>
        <div className="modal-head">
          <h2 style={{ margin:0, fontSize:20, fontWeight:800 }}>Aset Tetap Baru</h2>
          <button className="tb-icon-btn" onClick={onClose}><Icon.x/></button>
        </div>
        <form onSubmit={submit} style={{ padding:'20px 22px', display:'flex', flexDirection:'column', gap:14 }}>
          {error && <div style={{ padding:'10px 14px', background:'#fee2e2', color:'#991b1b', borderRadius:8, fontSize:13 }}>{error}</div>}
          <div style={{ display:'grid', gridTemplateColumns:'150px 1fr 200px', gap:12 }}>
            <FieldFA label="Kode">
              <input className="input" value={code} onChange={e=>setCode(e.target.value)} placeholder="FA-001" required/>
            </FieldFA>
            <FieldFA label="Nama">
              <input className="input" value={name} onChange={e=>setName(e.target.value)} placeholder="Forklift Toyota 2.5T" required/>
            </FieldFA>
            <FieldFA label="Kategori">
              <input className="input" value={category} onChange={e=>setCategory(e.target.value)} placeholder="Peralatan / Kendaraan"/>
            </FieldFA>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr 1fr', gap:12 }}>
            <FieldFA label="Tgl Perolehan">
              <input className="input" type="date" value={acquireDate} onChange={e=>setAcquireDate(e.target.value)} required/>
            </FieldFA>
            <FieldFA label="Harga Perolehan">
              <input className="input" type="number" min="0" value={acquireCost} onChange={e=>setAcquireCost(e.target.value)} required/>
            </FieldFA>
            <FieldFA label="Nilai Sisa">
              <input className="input" type="number" min="0" value={salvageValue} onChange={e=>setSalvageValue(e.target.value)}/>
            </FieldFA>
            <FieldFA label="Masa Manfaat (bln)">
              <input className="input" type="number" min="1" value={usefulLifeMonths} onChange={e=>setUsefulLifeMonths(e.target.value)}/>
            </FieldFA>
          </div>

          <div style={{ padding:'12px 14px', background:'var(--brand-50)', borderRadius:8, display:'flex', justifyContent:'space-between', alignItems:'center' }}>
            <span style={{ fontSize:12, color:'var(--ink-700)', fontWeight:600 }}>Penyusutan per bulan (straight-line)</span>
            <strong style={{ fontSize:18, color:'var(--brand-600)' }}>{fmtRp(monthly)}</strong>
          </div>

          <details>
            <summary style={{ fontSize:12, color:'var(--ink-500)', cursor:'pointer', fontWeight:600 }}>Akun yang dipakai (advanced)</summary>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:12, marginTop:10 }}>
              <FieldFA label="Kode Akun Aset">
                <input className="input" value={assetAccountCode} onChange={e=>setAssetAccountCode(e.target.value)}/>
              </FieldFA>
              <FieldFA label="Akum. Penyusutan">
                <input className="input" value={accumDepAccountCode} onChange={e=>setAccumDepAccountCode(e.target.value)}/>
              </FieldFA>
              <FieldFA label="Beban Penyusutan">
                <input className="input" value={depExpenseAccountCode} onChange={e=>setDepExpenseAccountCode(e.target.value)}/>
              </FieldFA>
            </div>
          </details>

          <div className="modal-foot" style={{ margin:'4px -22px -20px' }}>
            <button type="button" className="btn btn-secondary" onClick={onClose} disabled={busy}>Batal</button>
            <button type="submit" className="btn btn-primary" disabled={busy}>{busy ? 'Menyimpan…' : 'Simpan Aset'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function FAStat({ label, value, tone }) {
  const colors = { brand:'var(--brand-500)', green:'var(--green)', rose:'var(--rose)' };
  return (
    <div className="metric">
      <div className="metric-label">{label}</div>
      <div className="metric-value" style={{ color: tone ? colors[tone] : undefined }}>{value}</div>
    </div>
  );
}
function FieldFA({ label, children }) {
  return (
    <label style={{ display:'flex', flexDirection:'column', gap:6 }}>
      <span style={{ fontSize:12, fontWeight:600, color:'var(--ink-700)' }}>{label}</span>
      {children}
    </label>
  );
}

window.FixedAssetsPage = FixedAssetsPage;
