// budsjett-screens-4.jsx — Avtalekobling + Oppgavefordeling
// Eksporterer: BudAvtaler, BudOppgaver

// ════════════════════════════════════════════════════════════
// AVTALEKOBLING — trekk avtaler inn i budsjettet
// ════════════════════════════════════════════════════════════
function BudAvtaler({ data, versjonId, enhById, laast, onEndret }) {
  const [rediger, setRediger] = React.useState(null);
  const koblede = data.budAvtaler.filter(b => b.versjon_id === versjonId);
  const utenfor = window.budAvtalerUtenforBudsjett(data, versjonId);
  const avtaleById = Object.fromEntries(data.avtaler.map(a => [a.id, a]));
  const statusFarge = { forslag:'#e08d3c', innarbeidet:'#1b6a2e', ignorert:SK.soft };

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
      <div style={{ fontSize:13, color:SK.soft, lineHeight:1.6 }}>
        Trekk avtaler fra avtalemodulen inn i budsjettet, bearbeid beløp og konto, og innarbeid dem som budsjettlinjer.
        Nederst ser du avtaler som ennå ikke er vurdert for dette budsjettet.
      </div>

      {/* Koblede avtaler */}
      <Card padded={false}>
        <div style={{ padding:'14px 20px', borderBottom:'1px solid rgba(17,24,61,.07)', fontSize:14, fontWeight:600 }}>I budsjettet ({koblede.length})</div>
        {koblede.length===0 ? <div style={{ padding:24, textAlign:'center', color:SK.soft, fontSize:13 }}>Ingen avtaler koblet ennå.</div> : (
        <table className="ok-table" style={{ width:'100%' }}>
          <thead><tr><th style={{ paddingLeft:20 }}>Avtale</th><th>Avdeling</th><th>Konto</th><th style={{ textAlign:'right' }}>Budsjettbeløp</th><th>Status</th>{!laast && <th style={{ width:120 }}></th>}</tr></thead>
          <tbody>
            {koblede.map(b => { const a=avtaleById[b.avtale_id];
              return (<tr key={b.id}>
                <td style={{ paddingLeft:20 }}><div style={{ fontWeight:500 }}>{a?.name || '(slettet avtale)'}</div><div style={{ fontSize:11.5, color:SK.soft }}>{a?.motpart}</div></td>
                <td style={{ fontSize:12.5 }}>{enhById[b.avdeling_id]?.navn || '—'}</td>
                <td style={{ color:SK.soft }}>{b.konto || '—'}</td>
                <td style={{ textAlign:'right', fontWeight:500 }}>{window.budFmtKrFull(b.budsjett_belop)}</td>
                <td><span style={{ fontSize:11, fontWeight:600, padding:'2px 9px', borderRadius:99, background:statusFarge[b.status]+'22', color:statusFarge[b.status] }}>{b.status}</span></td>
                {!laast && <td><div style={{ display:'flex', gap:4 }}>
                  <button onClick={()=>setRediger(b)} style={budIkonKnapp} title="Rediger">✎</button>
                  {b.status==='forslag' && <button onClick={async()=>{ await window.budInnarbeidAvtale(b); onEndret(); }} style={{ ...budIkonKnapp, width:'auto', padding:'0 8px', fontSize:11 }} title="Innarbeid som budsjettlinje">→ linje</button>}
                  <button onClick={async()=>{ if(confirm('Fjerne koblingen?')){ await window.budDB.slett('bud_avtaler', b.id); onEndret(); }}} style={budIkonKnapp}>🗑</button>
                </div></td>}
              </tr>); })}
          </tbody>
        </table>)}
      </Card>

      {/* Avtaler utenfor budsjettet */}
      <Card padded={false}>
        <div style={{ padding:'14px 20px', borderBottom:'1px solid rgba(17,24,61,.07)', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
          <span style={{ fontSize:14, fontWeight:600 }}>Ikke i budsjettet ({utenfor.length})</span>
          {utenfor.length>0 && <span style={{ fontSize:11.5, color:'#e08d3c', fontWeight:600 }}>⚠ Bør vurderes</span>}
        </div>
        {utenfor.length===0 ? <div style={{ padding:24, textAlign:'center', color:SK.soft, fontSize:13 }}>Alle aktive avtaler er vurdert. 👍</div> : (
        <table className="ok-table" style={{ width:'100%' }}>
          <thead><tr><th style={{ paddingLeft:20 }}>Avtale</th><th>Type</th><th>Motpart</th><th style={{ textAlign:'right' }}>Årsverdi</th>{!laast && <th style={{ width:90 }}></th>}</tr></thead>
          <tbody>
            {utenfor.map(a => (
              <tr key={a.id}>
                <td style={{ paddingLeft:20, fontWeight:500 }}>{a.name}</td>
                <td style={{ fontSize:12, color:SK.soft }}>{a.type}</td>
                <td style={{ fontSize:12.5 }}>{a.motpart}</td>
                <td style={{ textAlign:'right' }}>{window.budFmtKrFull(a.arsverdi)}</td>
                {!laast && <td><Button size="sm" onClick={()=>setRediger({ ny:true, avtale_id:a.id, budsjett_belop:a.arsverdi, avtale_arsverdi:a.arsverdi, avdeling_id:a.enhet_id })}>+ Koble</Button></td>}
              </tr>
            ))}
          </tbody>
        </table>)}
      </Card>

      {rediger && <BudAvtaleModal kobling={rediger} data={data} versjonId={versjonId} avtaleById={avtaleById} onLukk={()=>setRediger(null)} onLagret={()=>{ setRediger(null); onEndret(); }} />}
    </div>
  );
}

function BudAvtaleModal({ kobling, data, versjonId, avtaleById, onLukk, onLagret }) {
  const ny = kobling.ny;
  const avtale = avtaleById[kobling.avtale_id];
  const [avdId, setAvdId]   = React.useState(kobling.avdeling_id || '');
  const [konto, setKonto]   = React.useState(kobling.konto || 3000);
  const [belop, setBelop]   = React.useState(kobling.budsjett_belop || avtale?.arsverdi || '');
  const [note, setNote]     = React.useState(kobling.note || (avtale ? avtale.name : ''));
  const [feil, setFeil]     = React.useState(null);
  const [lagrer, setLagrer] = React.useState(false);
  const lagre = async () => {
    if (!avdId) { setFeil('Avdeling er påkrevd.'); return; }
    setLagrer(true); setFeil(null);
    try {
      const felt = { avdeling_id:avdId, konto:Number(konto), budsjett_belop:Math.round(Number(belop)||0), note,
        avtale_arsverdi: kobling.avtale_arsverdi || avtale?.arsverdi || null };
      if (ny) await window.budDB.lagre('bud_avtaler', { versjon_id:versjonId, avtale_id:kobling.avtale_id, status:'forslag', ...felt });
      else await window.budDB.oppdater('bud_avtaler', kobling.id, felt);
      onLagret();
    } catch(e){ setFeil(e.message); setLagrer(false); }
  };
  return (
    <BudModal tittel={ny?'Koble avtale til budsjett':'Rediger avtalekobling'} onLukk={onLukk}>
      {feil && <div style={budFeil}>{feil}</div>}
      {avtale && <div style={{ background:SK.iceBlueLight, borderRadius:8, padding:'10px 14px', marginBottom:14, fontSize:12.5 }}>
        <b>{avtale.name}</b> · {avtale.motpart}<br/><span style={{ color:SK.soft }}>Årsverdi i avtalen: {window.budFmtKrFull(avtale.arsverdi)}</span>
      </div>}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'14px 16px' }}>
        <div style={{ gridColumn:'1/-1' }}><label style={budLBL}>Avdeling *</label>
          <select className="ok-input" value={avdId} onChange={e=>setAvdId(e.target.value)} style={budINP}>
            <option value="">— Velg —</option>{data.enheter.slice().sort((a,b)=>(a.avd_nr||'').localeCompare(b.avd_nr||'')).map(e=><option key={e.id} value={e.id}>{e.avd_nr} {e.navn}</option>)}
          </select></div>
        <div><label style={budLBL}>Konto</label>
          <select className="ok-input" value={konto} onChange={e=>setKonto(e.target.value)} style={budINP}>
            {data.kontoplan.map(k=><option key={k.konto} value={k.konto}>{k.konto} {k.navn}</option>)}
          </select></div>
        <div><label style={budLBL}>Budsjettbeløp (kr/år)</label><input className="ok-input" type="number" value={belop} onChange={e=>setBelop(e.target.value)} style={budINP} /></div>
        <div style={{ gridColumn:'1/-1' }}><label style={budLBL}>Notat</label><input className="ok-input" value={note} onChange={e=>setNote(e.target.value)} style={budINP} /></div>
      </div>
      <div style={{ display:'flex', gap:10, marginTop:18 }}>
        <Button variant="primary" onClick={lagre} disabled={lagrer}>{lagrer?'Lagrer…':'Lagre'}</Button>
        <Button onClick={onLukk}>Avbryt</Button>
      </div>
    </BudModal>
  );
}

// ════════════════════════════════════════════════════════════
// OPPGAVEFORDELING — deleger budsjettarbeid
// ════════════════════════════════════════════════════════════
function BudOppgaver({ data, versjonId, enhById, laast, onEndret }) {
  const [rediger, setRediger] = React.useState(null);
  const oppgaver = data.oppgaver.filter(o => o.versjon_id === versjonId);
  const profilById = Object.fromEntries(data.profiler.map(p => [p.id, p]));
  const statusFarge = { open:SK.soft, pagar:'#e08d3c', levert:'#586ba4', godkjent:'#1b6a2e' };
  const statusLabel = { open:'Åpen', pagar:'Pågår', levert:'Levert', godkjent:'Godkjent' };
  const rolleLabel = { ansvarlig:'Ansvarlig', bidragsyter:'Bidragsyter', leser:'Leser' };

  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', marginBottom:14, gap:12 }}>
        <div style={{ fontSize:13, color:SK.soft, lineHeight:1.6, maxWidth:620 }}>
          Deleger budsjettarbeid for en avdeling til en leder eller valgfri person. Tildelte personer får tilgang
          til <b>kun sin avdelings</b> budsjett — ansvarlig/bidragsyter kan redigere, leser kan kun se.
        </div>
        {!laast && <Button variant="primary" size="sm" icon={I.plus} onClick={()=>setRediger({ ny:true })}>Ny oppgave</Button>}
      </div>
      <Card padded={false}>
        <table className="ok-table" style={{ width:'100%' }}>
          <thead><tr><th style={{ paddingLeft:20 }}>Avdeling</th><th>Tildelt</th><th>Rolle</th><th>Oppgave</th><th>Frist</th><th>Status</th>{!laast && <th style={{ width:80 }}></th>}</tr></thead>
          <tbody>
            {oppgaver.length===0 && <tr><td colSpan={7} style={{ padding:24, textAlign:'center', color:SK.soft }}>Ingen oppgaver fordelt ennå.</td></tr>}
            {oppgaver.map(o => { const p=profilById[o.tildelt_id];
              return (<tr key={o.id}>
                <td style={{ paddingLeft:20, fontSize:12.5 }}>{enhById[o.avdeling_id]?.navn}</td>
                <td style={{ fontWeight:500 }}>{p?.navn || p?.epost || '—'}</td>
                <td><span style={{ fontSize:11, padding:'2px 8px', borderRadius:99, background:SK.iceBlueLight }}>{rolleLabel[o.rolle]}</span></td>
                <td>{o.tittel || '—'}</td>
                <td style={{ fontSize:12.5, color:SK.soft }}>{o.frist ? new Date(o.frist).toLocaleDateString('nb-NO',{day:'numeric',month:'short'}) : '—'}</td>
                <td><span style={{ fontSize:11, fontWeight:600, padding:'2px 9px', borderRadius:99, background:statusFarge[o.status]+'22', color:statusFarge[o.status] }}>{statusLabel[o.status]}</span></td>
                {!laast && <td><div style={{ display:'flex', gap:4 }}>
                  <button onClick={()=>setRediger(o)} style={budIkonKnapp}>✎</button>
                  <button onClick={async()=>{ if(confirm('Slette oppgaven?')){ await window.budDB.slett('bud_oppgaver', o.id); onEndret(); }}} style={budIkonKnapp}>🗑</button>
                </div></td>}
              </tr>); })}
          </tbody>
        </table>
      </Card>
      {rediger && <BudOppgaveModal oppgave={rediger} data={data} versjonId={versjonId} onLukk={()=>setRediger(null)} onLagret={()=>{ setRediger(null); onEndret(); }} />}
    </div>
  );
}

function BudOppgaveModal({ oppgave, data, versjonId, onLukk, onLagret }) {
  const ny = oppgave.ny;
  const [avdId, setAvdId]     = React.useState(oppgave.avdeling_id || '');
  const [tildelt, setTildelt] = React.useState(oppgave.tildelt_id || '');
  const [rolle, setRolle]     = React.useState(oppgave.rolle || 'ansvarlig');
  const [tittel, setTittel]   = React.useState(oppgave.tittel || '');
  const [beskrivelse, setBeskrivelse] = React.useState(oppgave.beskrivelse || '');
  const [frist, setFrist]     = React.useState(oppgave.frist || '');
  const [status, setStatus]   = React.useState(oppgave.status || 'open');
  const [feil, setFeil]       = React.useState(null);
  const [lagrer, setLagrer]   = React.useState(false);
  const lagre = async () => {
    if (!avdId || !tildelt) { setFeil('Avdeling og person er påkrevd.'); return; }
    setLagrer(true); setFeil(null);
    try {
      const felt = { avdeling_id:avdId, tildelt_id:tildelt, rolle, tittel, beskrivelse, frist:frist||null, status };
      if (ny) await window.budDB.lagre('bud_oppgaver', { versjon_id:versjonId, ...felt });
      else await window.budDB.oppdater('bud_oppgaver', oppgave.id, felt);
      onLagret();
    } catch(e){ setFeil(e.message); setLagrer(false); }
  };
  return (
    <BudModal tittel={ny?'Ny budsjettoppgave':'Rediger oppgave'} onLukk={onLukk} bred>
      {feil && <div style={budFeil}>{feil}</div>}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'14px 16px' }}>
        <div><label style={budLBL}>Avdeling *</label>
          <select className="ok-input" value={avdId} onChange={e=>setAvdId(e.target.value)} style={budINP}>
            <option value="">— Velg —</option>{data.enheter.slice().sort((a,b)=>(a.avd_nr||'').localeCompare(b.avd_nr||'')).map(e=><option key={e.id} value={e.id}>{e.avd_nr} {e.navn}</option>)}
          </select></div>
        <div><label style={budLBL}>Tildel til *</label>
          <select className="ok-input" value={tildelt} onChange={e=>setTildelt(e.target.value)} style={budINP}>
            <option value="">— Velg person —</option>{data.profiler.slice().sort((a,b)=>(a.navn||'').localeCompare(b.navn||'')).map(p=><option key={p.id} value={p.id}>{p.navn || p.epost}</option>)}
          </select></div>
        <div><label style={budLBL}>Rolle</label>
          <select className="ok-input" value={rolle} onChange={e=>setRolle(e.target.value)} style={budINP}>
            <option value="ansvarlig">Ansvarlig (kan redigere)</option>
            <option value="bidragsyter">Bidragsyter (kan redigere)</option>
            <option value="leser">Leser (kun se)</option>
          </select></div>
        <div><label style={budLBL}>Status</label>
          <select className="ok-input" value={status} onChange={e=>setStatus(e.target.value)} style={budINP}>
            <option value="open">Åpen</option><option value="pagar">Pågår</option><option value="levert">Levert</option><option value="godkjent">Godkjent</option>
          </select></div>
        <div><label style={budLBL}>Tittel</label><input className="ok-input" value={tittel} onChange={e=>setTittel(e.target.value)} style={budINP} placeholder="f.eks. Budsjettér drift 2026" /></div>
        <div><label style={budLBL}>Frist</label><input className="ok-input" type="date" value={frist} onChange={e=>setFrist(e.target.value)} style={budINP} /></div>
        <div style={{ gridColumn:'1/-1' }}><label style={budLBL}>Beskrivelse</label><input className="ok-input" value={beskrivelse} onChange={e=>setBeskrivelse(e.target.value)} style={budINP} /></div>
      </div>
      <div style={{ fontSize:11.5, color:SK.soft, marginTop:10, lineHeight:1.5 }}>
        Personen får tilgang til kun denne avdelingens budsjett. Ingen detaljer fra andre avdelinger blir synlige.
      </div>
      <div style={{ display:'flex', gap:10, marginTop:18 }}>
        <Button variant="primary" onClick={lagre} disabled={lagrer}>{lagrer?'Lagrer…':'Lagre'}</Button>
        <Button onClick={onLukk}>Avbryt</Button>
      </div>
    </BudModal>
  );
}

Object.assign(window, { BudAvtaler, BudOppgaver });
