// Suppliers list + detail page

const SupplierDetail = ({ supplier, onClose, role }) => {
  const { DOCUMENTS, POS, SAIF_COMPANIES, STAFF } = window.SaifData;
  const [tab, setTab] = React.useState('profile');
  const docs = DOCUMENTS.filter(d => d.supplierId === supplier.id);
  const pos = POS.filter(p => p.supplierId === supplier.id);
  const cos = supplier.companies.map(id => SAIF_COMPANIES.find(c => c.id === id));
  const [showApprove, setShowApprove] = React.useState(false);

  return (
    <div className="page">
      <div style={{ marginBottom: 16 }}>
        <button className="btn btn-ghost btn-sm" onClick={onClose}><Icon name="chevronLeft" size={13}/> Back to suppliers</button>
      </div>
      <div className="page-header">
        <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
          <Avatar name={supplier.name} size="xl" tone={supplier.tone}/>
          <div>
            <h1 className="page-title">{supplier.name}</h1>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 6, flexWrap: 'wrap' }}>
              <Badge kind={statusToBadge(supplier.status)}>{supplier.status}</Badge>
              <span className="text-mute text-md">{supplier.industry}</span>
              <span className="text-mute text-md">·</span>
              <span className="text-mute text-md">{supplier.city}, {supplier.country}</span>
              <span className="text-mute text-md">·</span>
              <span className="text-mono text-xs text-mute">TL {supplier.tradeLicense}</span>
            </div>
            <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
              {cos.map(c => (
                <span key={c.id} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 9px', borderRadius: 5, background: 'var(--surface-3)', fontSize: 11, fontWeight: 500 }}>
                  <span className="company-dot" style={{ background: c.color, width: 6, height: 6, borderRadius: '50%' }}></span>
                  {c.name}
                </span>
              ))}
            </div>
          </div>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="mail" size={14}/> Message</button>
          <button className="btn"><Icon name="edit" size={14}/> Edit</button>
          {supplier.status === 'pending' && role === 'admin' && (
            <button className="btn btn-accent" onClick={() => setShowApprove(true)}>
              <Icon name="check" size={14}/> Approve supplier
            </button>
          )}
        </div>
      </div>

      <div className="kpi-grid" style={{ marginBottom: 18 }}>
        <KPICard label="Total POs" value={supplier.poCount} meta="lifetime" icon="po"/>
        <KPICard label="Open Value" value={fmtCurrency(supplier.openValue)} meta="across active POs" icon="chart"/>
        <KPICard label="Documents" value={docs.length} meta={`${docs.filter(d => d.status === 'red').length} expired, ${docs.filter(d => d.status === 'amber').length} expiring`} icon="docs"/>
        <KPICard label="Registered" value={fmtDate(supplier.registered).split(' ').slice(0, 2).join(' ')} meta={fmtDate(supplier.registered).split(' ')[2]} icon="clock"/>
      </div>

      <div className="tabs">
        {[
          { id: 'profile', label: 'Profile' },
          { id: 'documents', label: 'Documents', count: docs.length },
          { id: 'contacts', label: 'Contacts' },
          { id: 'bank', label: 'Bank Details' },
          { id: 'pos', label: 'POs & Quotes', count: pos.length },
          { id: 'activity', label: 'Activity Log' },
        ].map(t => (
          <button key={t.id} className="tab" data-active={tab === t.id} onClick={() => setTab(t.id)}>
            {t.label} {t.count !== undefined && <span className="tab-count">{t.count}</span>}
          </button>
        ))}
      </div>

      {tab === 'profile' && (
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 18 }}>
          <div className="card">
            <div className="card-header"><h3 className="card-title">Company information</h3></div>
            <div className="card-body" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px 24px', fontSize: 13 }}>
              <div><div className="text-xs text-mute mb-4">Legal name</div>{supplier.name}</div>
              <div><div className="text-xs text-mute mb-4">Industry</div>{supplier.industry}</div>
              <div><div className="text-xs text-mute mb-4">Trade License #</div><span className="text-mono">{supplier.tradeLicense}</span></div>
              <div><div className="text-xs text-mute mb-4">VAT (TRN)</div><span className="text-mono">{supplier.vat}</span></div>
              <div><div className="text-xs text-mute mb-4">City</div>{supplier.city}</div>
              <div><div className="text-xs text-mute mb-4">Country</div>{supplier.country}</div>
              <div><div className="text-xs text-mute mb-4">Primary contact</div>{supplier.contact}</div>
              <div><div className="text-xs text-mute mb-4">Email</div>{supplier.email}</div>
              <div><div className="text-xs text-mute mb-4">Phone</div><span className="text-mono">{supplier.phone}</span></div>
              <div><div className="text-xs text-mute mb-4">Registered</div>{fmtDate(supplier.registered)}</div>
            </div>
          </div>
          <div className="card">
            <div className="card-header"><h3 className="card-title">Engagement</h3></div>
            <div className="card-body">
              {cos.map(c => (
                <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 0', borderBottom: '1px solid var(--line-2)' }}>
                  <span className="company-dot" style={{ background: c.color, width: 10, height: 10, borderRadius: '50%' }}></span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{c.name}</div>
                    <div style={{ fontSize: 11, color: 'var(--text-mute)' }}>{c.industry}</div>
                  </div>
                  <span className="text-mono text-xs text-mute">{c.code}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {tab === 'documents' && (
        <div className="card">
          <table className="tbl">
            <thead><tr><th>Type</th><th>File</th><th>Uploaded</th><th>Expires</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {docs.map(d => (
                <tr key={d.id}>
                  <td style={{ fontWeight: 500 }}>{d.type}</td>
                  <td className="tbl-mono">{d.fileName}</td>
                  <td>{fmtDate(d.uploaded)}</td>
                  <td className="text-mono">{fmtDate(d.expires)}</td>
                  <td><DocPill status={d.status}>{d.status === 'red' ? 'Expired / soon' : d.status === 'amber' ? 'Expiring 30d' : 'Valid'}</DocPill></td>
                  <td><button className="btn btn-sm btn-ghost"><Icon name="eye" size={13}/></button></td>
                </tr>
              ))}
              {docs.length === 0 && <tr><td colSpan="6" style={{ padding: 36, textAlign: 'center', color: 'var(--text-mute)' }}>No documents on file yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'contacts' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 14 }}>
          {[
            { name: supplier.contact, role: 'Director / Primary', email: supplier.email, phone: supplier.phone },
            { name: 'Sarah Khan', role: 'Finance', email: 'finance@' + supplier.email.split('@')[1], phone: '+971 50 882 4410' },
            { name: 'Ahmed Reza', role: 'Operations', email: 'ops@' + supplier.email.split('@')[1], phone: '+971 50 117 9920' },
          ].map((c, i) => (
            <div key={i} className="card">
              <div className="card-body">
                <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                  <Avatar name={c.name} size="lg" tone={supplier.tone}/>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600, fontSize: 14 }}>{c.name}</div>
                    <div style={{ fontSize: 12, color: 'var(--text-mute)' }}>{c.role}</div>
                    <div style={{ marginTop: 8, fontSize: 12, display: 'flex', flexDirection: 'column', gap: 4 }}>
                      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}><Icon name="mail" size={12} className="text-mute"/> {c.email}</div>
                      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}><Icon name="phone" size={12} className="text-mute"/> <span className="text-mono">{c.phone}</span></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {tab === 'bank' && (
        <div className="card" style={{ maxWidth: 640 }}>
          <div className="card-header"><h3 className="card-title">Banking details</h3></div>
          <div className="card-body" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px 24px', fontSize: 13 }}>
            <div><div className="text-xs text-mute mb-4">Account name</div>{supplier.name}</div>
            <div><div className="text-xs text-mute mb-4">Bank name</div>Emirates NBD</div>
            <div><div className="text-xs text-mute mb-4">IBAN</div><span className="text-mono">AE07 0331 2345 6789 1011 00</span></div>
            <div><div className="text-xs text-mute mb-4">SWIFT/BIC</div><span className="text-mono">EBILAEAD</span></div>
            <div><div className="text-xs text-mute mb-4">Branch</div>{supplier.city} Main</div>
            <div><div className="text-xs text-mute mb-4">Currency</div>AED · USD</div>
          </div>
        </div>
      )}

      {tab === 'pos' && (
        <div className="card">
          <table className="tbl">
            <thead><tr><th>Reference</th><th>Description</th><th>Company</th><th>Date</th><th style={{ textAlign: 'right' }}>Amount</th><th>Status</th></tr></thead>
            <tbody>
              {pos.map(p => {
                const co = SAIF_COMPANIES.find(c => c.id === p.company);
                return (
                  <tr key={p.id}>
                    <td className="tbl-mono">{p.id}</td>
                    <td>{p.desc}</td>
                    <td><span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span className="company-dot" style={{ background: co.color, width: 7, height: 7, borderRadius: '50%' }}></span>{co.code}</span></td>
                    <td>{fmtDate(p.date)}</td>
                    <td style={{ textAlign: 'right', fontWeight: 600 }}>{fmtCurrency(p.amount)}</td>
                    <td><Badge kind={statusToBadge(p.status)}>{p.status}</Badge></td>
                  </tr>
                );
              })}
              {pos.length === 0 && <tr><td colSpan="6" style={{ padding: 36, textAlign: 'center', color: 'var(--text-mute)' }}>No POs or quotes yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'activity' && (
        <div className="card">
          <div className="card-body">
            {[
              { actor: 'me_admin', verb: 'updated trade license info on', target: supplier.name, time: '2 hours ago', icon: 'edit' },
              { actor: 'u3', verb: 'flagged document expiry on', target: supplier.name, time: 'Yesterday', icon: 'alert' },
              { actor: 'u1', verb: 'added new contact to', target: supplier.name, time: '3 days ago', icon: 'users' },
              { actor: 'me_admin', verb: 'approved', target: supplier.name, time: fmtDate(supplier.registered), icon: 'check' },
            ].map((a, i) => {
              const u = STAFF.find(s => s.id === a.actor) || window.SaifData.ME_ADMIN;
              return (
                <div key={i} className="activity-item">
                  <div className={`activity-icon ${a.icon}`}><Icon name={a.icon} size={13}/></div>
                  <div style={{ flex: 1 }}>
                    <div className="activity-text"><b>{u.name}</b> {a.verb} <b>{a.target}</b></div>
                    <div className="activity-time">{a.time}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      <ApproveSupplierModal open={showApprove} onClose={() => setShowApprove(false)} supplier={supplier}/>
    </div>
  );
};

const ApproveSupplierModal = ({ open, onClose, supplier }) => {
  if (!supplier) return null;
  const submit = () => {
    window.showToast({ title: 'Approval email sent', body: `Sent to ${supplier.contact} <${supplier.email}>`, icon: 'mail' });
    onClose();
  };
  return (
    <Modal open={open} onClose={onClose} title="Approve supplier" size="lg"
      footer={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn btn-accent" onClick={submit}><Icon name="send" size={13}/> Approve & send email</button>
      </>}>
      <div style={{ marginBottom: 14, padding: 12, background: 'var(--green-soft)', borderRadius: 8, fontSize: 13, color: 'oklch(0.42 0.10 145)', display: 'flex', gap: 10, alignItems: 'center' }}>
        <Icon name="check" size={16}/>
        Approving will move <b>{supplier.name}</b> to active status, allow PO issuance, and send a notification email to the primary contact.
      </div>
      <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text-mute)', marginBottom: 8 }}>Email preview</div>
      <div className="email-preview">
        <div className="email-head">
          <div className="email-head-row"><span>From</span><span>procurement@saifalkhyeli.ae</span></div>
          <div className="email-head-row"><span>To</span><span>{supplier.email}</span></div>
          <div className="email-head-row"><span>Subject</span><span><b>Welcome to Saif Al Khyeli Group — your supplier registration is approved</b></span></div>
        </div>
        <div className="email-body">
          <p>Dear {supplier.contact},</p>
          <p>We are pleased to inform you that your registration as a supplier with Saif Al Khyeli Group has been approved. {supplier.name} is now active in our system and eligible to receive purchase orders from {supplier.companies.length} group {supplier.companies.length === 1 ? 'company' : 'companies'}.</p>
          <p><b>Next steps:</b> Sign in to the supplier portal to track POs, upload renewed documents, and message your assigned procurement officer.</p>
          <p style={{ marginBottom: 4 }}>Welcome aboard,</p>
          <p style={{ margin: 0 }}><b>Saif Al Khyeli Group Procurement</b></p>
        </div>
      </div>
    </Modal>
  );
};

const SuppliersPage = ({ company, openSupplier, role }) => {
  const { SUPPLIERS, SAIF_COMPANIES } = window.SaifData;
  const [filter, setFilter] = React.useState({ status: 'all', industry: 'all' });
  const [search, setSearch] = React.useState('');

  let list = SUPPLIERS;
  if (filter.status !== 'all') list = list.filter(s => s.status === filter.status);
  if (filter.industry !== 'all') list = list.filter(s => s.industry === filter.industry);
  if (company !== 'all') list = list.filter(s => s.companies.includes(company));
  if (search) list = list.filter(s => s.name.toLowerCase().includes(search.toLowerCase()));

  const industries = [...new Set(SUPPLIERS.map(s => s.industry))];

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Suppliers</h1>
          <p className="page-subtitle">{SUPPLIERS.length} suppliers across the group · {SUPPLIERS.filter(s => s.status === 'pending').length} awaiting approval</p>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="download" size={14}/> Export CSV</button>
          <button className="btn btn-primary"><Icon name="plus" size={14}/> Invite supplier</button>
        </div>
      </div>

      <div className="filter-bar">
        <div style={{ position: 'relative', minWidth: 280 }}>
          <Icon name="search" size={13} className="text-mute" />
          <input className="form-control" placeholder="Search suppliers…" value={search} onChange={e => setSearch(e.target.value)}
            style={{ paddingLeft: 32 }}/>
          <span style={{ position: 'absolute', left: 10, top: 9, color: 'var(--text-mute)' }}><Icon name="search" size={13}/></span>
        </div>
        {['all', 'approved', 'pending', 'rejected'].map(s => (
          <button key={s} className="filter-chip" data-active={filter.status === s} onClick={() => setFilter(f => ({ ...f, status: s }))}>
            {s === 'all' ? 'All status' : s}
          </button>
        ))}
        <select className="filter-chip" value={filter.industry} onChange={e => setFilter(f => ({ ...f, industry: e.target.value }))} style={{ padding: '5px 10px' }}>
          <option value="all">All industries</option>
          {industries.map(i => <option key={i} value={i}>{i}</option>)}
        </select>
        <div style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--text-mute)' }}>{list.length} results</div>
      </div>

      <div className="card">
        <table className="tbl">
          <thead>
            <tr>
              <th>Supplier</th>
              <th>Industry</th>
              <th>Group company</th>
              <th>Documents</th>
              <th>POs</th>
              <th style={{ textAlign: 'right' }}>Open value</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {list.map(s => {
              const cos = s.companies.map(id => SAIF_COMPANIES.find(c => c.id === id));
              return (
                <tr key={s.id} onClick={() => openSupplier(s.id)}>
                  <td>
                    <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                      <Avatar name={s.name} size="md" tone={s.tone}/>
                      <div>
                        <div style={{ fontWeight: 500, color: 'var(--ink)' }}>{s.name}</div>
                        <div className="text-xs text-mute">{s.contact} · {s.city}</div>
                      </div>
                    </div>
                  </td>
                  <td>{s.industry}</td>
                  <td>
                    <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                      {cos.map(c => (
                        <span key={c.id} title={c.name} style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 6px', borderRadius: 4, background: 'var(--surface-3)', fontSize: 10, fontWeight: 600, fontFamily: 'var(--font-mono)' }}>
                          <span className="company-dot" style={{ background: c.color, width: 6, height: 6, borderRadius: '50%' }}></span>
                          {c.code}
                        </span>
                      ))}
                    </div>
                  </td>
                  <td><DocPill status={s.docHealth}>{s.docHealth === 'green' ? 'All valid' : s.docHealth === 'amber' ? 'Expiring' : 'Expired'}</DocPill></td>
                  <td><span className="text-mono">{s.poCount}</span></td>
                  <td style={{ textAlign: 'right', fontWeight: 500 }}>{s.openValue > 0 ? fmtCurrency(s.openValue) : '—'}</td>
                  <td><Badge kind={statusToBadge(s.status)}>{s.status}</Badge></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

Object.assign(window, { SuppliersPage, SupplierDetail, ApproveSupplierModal });
