// Proposals — Supplier (inbound) and Customer (outbound)
// Iteration loop: submit → review → request changes → resubmit → approve

const PROPOSAL_STATUS_META = {
  'draft':              { label: 'Draft',              kind: 'grey'   },
  'submitted':          { label: 'Submitted',          kind: 'blue'   },
  'under-review':       { label: 'Under review',       kind: 'amber'  },
  'revision-requested': { label: 'Revision requested', kind: 'amber'  },
  'resubmitted':        { label: 'Resubmitted',        kind: 'blue'   },
  'approved':           { label: 'Approved',           kind: 'green'  },
  'rejected':           { label: 'Rejected',           kind: 'red'    },
};

const ownerCopy = (proposal) => {
  if (!proposal.owner) return null;
  if (proposal.owner === 'saif')     return 'Awaiting Saif review';
  if (proposal.owner === 'supplier') return `Awaiting ${proposal.party}`;
  if (proposal.owner === 'customer') return `Awaiting ${proposal.party}`;
  return null;
};

const TypeChips = ({ type, size = 'sm' }) => {
  const has = (t) => type === t || type === 'both';
  return (
    <span className="prop-types">
      {has('technical') && <span className={`prop-type prop-type-tech prop-type-${size}`}><Icon name="file" size={11}/> Technical</span>}
      {has('commercial') && <span className={`prop-type prop-type-comm prop-type-${size}`}><Icon name="file" size={11}/> Commercial</span>}
    </span>
  );
};

const ProposalsPage = ({ kind, role, openProposal, openProposalId, setPage }) => {
  const { PROPOSALS, SAIF_COMPANIES } = window.SaifData;
  const [filter, setFilter] = React.useState('all');

  if (openProposalId) {
    const p = PROPOSALS.find(x => x.id === openProposalId);
    if (p) return <ProposalDetail proposal={p} onClose={() => openProposal(null)} role={role}/>;
  }

  const list = PROPOSALS.filter(p => p.kind === kind);
  const filtered = list.filter(p => {
    if (filter === 'all') return true;
    if (filter === 'awaiting-us')   return p.owner === 'saif';
    if (filter === 'awaiting-them') return p.owner === 'supplier' || p.owner === 'customer';
    if (filter === 'approved') return p.status === 'approved';
    if (filter === 'rejected') return p.status === 'rejected';
    if (filter === 'active')   return p.status !== 'approved' && p.status !== 'rejected';
    return true;
  });

  const kpiActive    = list.filter(p => p.status !== 'approved' && p.status !== 'rejected').length;
  const kpiAwaitUs   = list.filter(p => p.owner === 'saif').length;
  const kpiAwaitThem = list.filter(p => p.owner === 'supplier' || p.owner === 'customer').length;
  const kpiApproved  = list.filter(p => p.status === 'approved').length;

  const isSupplier = kind === 'supplier';
  const heading    = isSupplier ? 'Supplier Proposals' : 'Customer Proposals';
  const sub        = isSupplier
    ? 'Proposals received from suppliers — technical, commercial, or both. Reviewed by Saif and iterated until approval.'
    : 'Quotes sent to customers — technical, commercial, or both. Iterated with the customer until approval.';

  const coById = (id) => SAIF_COMPANIES.find(c => c.id === id);

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">{heading}</h1>
          <p className="page-subtitle">{sub}</p>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="download" size={14}/> Export</button>
          <button className="btn btn-primary"><Icon name="plus" size={14}/> New {isSupplier ? 'request' : 'quote'}</button>
        </div>
      </div>

      <div className="kpi-grid" style={{ marginBottom: 18 }}>
        <KPICard label="Active" value={kpiActive} meta="in progress" icon="workflow"/>
        <KPICard label="Awaiting Saif" value={kpiAwaitUs} meta="needs our action" icon="inbox"/>
        <KPICard label={isSupplier ? 'Awaiting supplier' : 'Awaiting customer'} value={kpiAwaitThem} meta="with the other side" icon="clock"/>
        <KPICard label="Approved" value={kpiApproved} meta="ready for PO" icon="check"/>
      </div>

      <div className="tabs" style={{ marginBottom: 14 }}>
        {[
          { id: 'all',           label: 'All',           count: list.length },
          { id: 'active',        label: 'Active',        count: kpiActive },
          { id: 'awaiting-us',   label: 'Awaiting Saif', count: kpiAwaitUs },
          { id: 'awaiting-them', label: isSupplier ? 'Awaiting supplier' : 'Awaiting customer', count: kpiAwaitThem },
          { id: 'approved',     label: 'Approved',     count: kpiApproved },
          { id: 'rejected',     label: 'Rejected',     count: list.filter(p => p.status === 'rejected').length },
        ].map(t => (
          <button key={t.id} className="tab" data-active={filter === t.id} onClick={() => setFilter(t.id)}>
            {t.label} <span className="tab-count">{t.count}</span>
          </button>
        ))}
      </div>

      {filtered.length === 0 ? (
        <div className="card"><div className="empty-state">
          <Icon name="file" size={28} className="text-dim"/>
          <h3>No proposals here yet</h3>
          <p>Try a different filter, or create a new {isSupplier ? 'request' : 'quote'}.</p>
        </div></div>
      ) : (
        <div className="card">
          <table className="tbl prop-tbl">
            <thead>
              <tr>
                <th>Number</th>
                <th>Proposal</th>
                <th>Company</th>
                <th>Type</th>
                <th style={{ textAlign: 'right' }}>Value</th>
                <th>Updated</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(p => {
                const co = coById(p.company);
                const meta = PROPOSAL_STATUS_META[p.status];
                return (
                  <tr key={p.id} onClick={() => openProposal(p.id)}>
                    <td className="text-mono text-xs" style={{ fontWeight: 600, color: 'var(--accent-ink)', whiteSpace: 'nowrap' }}>{p.number}</td>
                    <td>
                      <div className="prop-row-title">{p.title}</div>
                      <div className="prop-row-party">{p.party}</div>
                    </td>
                    <td>
                      <span className="prop-row-company">
                        <span className="company-dot" style={{ background: co.color }}></span>
                        {co.name}
                      </span>
                    </td>
                    <td><TypeChips type={p.type}/></td>
                    <td className="text-mono" style={{ textAlign: 'right', fontWeight: 600, color: 'var(--ink)' }}>{fmtCurrency(p.value)}</td>
                    <td className="text-xs text-mute">{fmtDate(p.updated)}</td>
                    <td><Badge kind={meta.kind}>{meta.label}</Badge></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

const ProposalDetail = ({ proposal, onClose, role }) => {
  const { SAIF_COMPANIES } = window.SaifData;
  const [activeVersion, setActiveVersion] = React.useState(proposal.versions[0].v);
  const initialTab = proposal.versions[0].technical ? 'technical' : 'commercial';
  const [tab, setTab] = React.useState(initialTab);
  const [requestingChanges, setRequestingChanges] = React.useState(false);
  const [draftComment, setDraftComment] = React.useState('');

  const co = SAIF_COMPANIES.find(c => c.id === proposal.company);
  const meta = PROPOSAL_STATUS_META[proposal.status];
  const isSupplierKind = proposal.kind === 'supplier';
  const version = proposal.versions.find(v => v.v === activeVersion) || proposal.versions[0];
  const file = version[tab];

  const owner = ownerCopy(proposal);
  const isFinal = proposal.status === 'approved' || proposal.status === 'rejected';

  // Comments grouped by version
  const commentsByVersion = proposal.versions.map(v => ({
    v: v.v,
    items: proposal.comments.filter(c => c.against === v.v),
  })).filter(g => g.items.length > 0);

  return (
    <div className="page">
      <div style={{ marginBottom: 16 }}>
        <button className="btn btn-ghost btn-sm" onClick={onClose}>
          <Icon name="chevronLeft" size={13}/> Back to {isSupplierKind ? 'supplier' : 'customer'} proposals
        </button>
      </div>

      <div className="page-header">
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="text-mono text-xs" style={{ color: 'var(--accent-ink)', fontWeight: 600, marginBottom: 4 }}>{proposal.number}</div>
          <h1 className="page-title">{proposal.title}</h1>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 6, flexWrap: 'wrap' }}>
            <Badge kind={meta.kind}>{meta.label}</Badge>
            <span className="text-mute text-md">{proposal.party}</span>
            <span className="text-mute text-md">·</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12 }}>
              <span className="company-dot" style={{ background: co.color }}></span> {co.name}
            </span>
            <span className="text-mute text-md">·</span>
            <span className="text-md" style={{ fontWeight: 600 }}>{fmtCurrency(proposal.value)}</span>
          </div>
        </div>
        <div className="page-actions">
          {!isFinal && proposal.owner === 'saif' && (
            <>
              <button className="btn" onClick={() => setRequestingChanges(true)}>
                <Icon name="edit" size={14}/> Request changes
              </button>
              <button className="btn btn-accent">
                <Icon name="check" size={14}/> Approve
              </button>
            </>
          )}
          {!isFinal && proposal.owner !== 'saif' && (
            <button className="btn btn-ghost" disabled>
              <Icon name="clock" size={14}/> Awaiting {isSupplierKind ? 'supplier' : 'customer'}
            </button>
          )}
          {isFinal && (
            <button className="btn btn-ghost" disabled>
              <Icon name="check" size={14}/> {meta.label}
            </button>
          )}
        </div>
      </div>

      {owner && !isFinal && (
        <div className={`prop-status-banner prop-status-${proposal.owner}`}>
          <Icon name={proposal.owner === 'saif' ? 'inbox' : 'clock'} size={14}/>
          <span><b>{owner}</b> · {proposal.status === 'revision-requested' ? 'Changes requested — supplier to upload a new version.' :
                                  proposal.status === 'submitted' ? 'New submission — open and review.' :
                                  proposal.status === 'resubmitted' ? 'Updated version submitted — reviewers to revisit comments.' :
                                  'Currently being reviewed.'}</span>
        </div>
      )}

      <div className="prop-detail-grid">
        {/* LEFT: Documents */}
        <div className="card">
          <div className="card-header" style={{ paddingBottom: 0 }}>
            <div>
              <h3 className="card-title">Documents</h3>
              <div className="card-sub">Attachments uploaded by {isSupplierKind ? 'the supplier' : 'Saif'}</div>
            </div>
            {proposal.owner === (isSupplierKind ? 'supplier' : 'saif') && (
              <button className="btn btn-sm btn-primary"><Icon name="upload" size={12}/> Upload new version</button>
            )}
          </div>

          <div className="prop-doc-tabs">
            {['technical', 'commercial'].map(t => {
              const exists = proposal.versions.some(v => v[t]);
              if (!exists) return null;
              return (
                <button key={t} className="prop-doc-tab" data-active={tab === t} onClick={() => setTab(t)}>
                  <Icon name="file" size={12}/> {t === 'technical' ? 'Technical' : 'Commercial'}
                </button>
              );
            })}
          </div>

          <div className="prop-version-strip">
            {proposal.versions.map((v, i) => (
              <button key={v.v} className="prop-version" data-active={activeVersion === v.v} onClick={() => setActiveVersion(v.v)}>
                <span className="prop-version-tag">v{v.v}</span>
                {i === 0 && <span className="prop-version-current">current</span>}
              </button>
            ))}
          </div>

          <div className="card-body">
            {file ? (
              <div className="prop-file-card">
                <div className="prop-file-icon"><Icon name="file" size={20}/></div>
                <div style={{ flex: 1 }}>
                  <div className="prop-file-name">{file.fileName}</div>
                  <div className="prop-file-meta">
                    {file.size} · uploaded by {file.uploadedBy} · {file.uploadedAt}
                  </div>
                </div>
                <button className="btn btn-sm"><Icon name="eye" size={12}/> Preview</button>
                <button className="btn btn-sm"><Icon name="download" size={12}/></button>
              </div>
            ) : (
              <div className="prop-file-empty">
                No {tab} document attached for v{activeVersion}.
              </div>
            )}

            <div className="prop-doc-preview">
              <Icon name="file" size={36} className="text-dim"/>
              <div style={{ marginTop: 10 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>
                  {tab === 'technical' ? 'Technical proposal' : 'Commercial proposal'} · v{activeVersion}
                </div>
                <div style={{ fontSize: 12, color: 'var(--text-mute)', marginTop: 4 }}>
                  Inline document viewer — click <b>Preview</b> to open in a side-by-side panel
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* RIGHT: Comments */}
        <div className="card prop-comments-card">
          <div className="card-header">
            <div>
              <h3 className="card-title">Discussion</h3>
              <div className="card-sub">{proposal.comments.length} comments across {proposal.versions.length} version{proposal.versions.length > 1 ? 's' : ''}</div>
            </div>
          </div>

          <div className="prop-comments">
            {commentsByVersion.map(group => (
              <div key={group.v} className="prop-comment-group">
                <div className="prop-comment-anchor">
                  <span className="prop-comment-anchor-line"></span>
                  <span className="prop-comment-anchor-tag">v{group.v}</span>
                  <span className="prop-comment-anchor-line"></span>
                </div>
                {group.items.map(c => (
                  <div key={c.id} className={`prop-comment prop-comment-${c.side}`}>
                    <Avatar name={c.actor} size="sm"/>
                    <div className="prop-comment-body">
                      <div className="prop-comment-head">
                        <span className="prop-comment-actor">{c.actor}</span>
                        <span className={`prop-comment-side prop-comment-side-${c.side}`}>{c.role}</span>
                        <span className="prop-comment-time">{c.time}</span>
                      </div>
                      <div className="prop-comment-text">{c.text}</div>
                    </div>
                  </div>
                ))}
              </div>
            ))}
          </div>

          {!isFinal && (
            <div className="prop-comment-input">
              <textarea
                className="form-control"
                placeholder={requestingChanges ? 'Describe what needs to change for the next version…' : 'Add a comment on v' + version.v + '…'}
                value={draftComment}
                onChange={e => setDraftComment(e.target.value)}
                rows={3}
              />
              <div className="prop-comment-input-actions">
                <button className="btn btn-sm btn-ghost"><Icon name="paperclip" size={12}/></button>
                <span style={{ flex: 1 }}/>
                {requestingChanges && (
                  <button className="btn btn-sm" onClick={() => { setRequestingChanges(false); setDraftComment(''); }}>Cancel</button>
                )}
                <button className="btn btn-sm btn-primary" disabled={!draftComment.trim()}>
                  <Icon name="send" size={12}/> {requestingChanges ? 'Send & request changes' : 'Comment'}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ProposalsPage, ProposalDetail });
