// Tenant billing: invoices list, invoice detail, payment modal, account

const TenantInvoices = ({ tenantId, setRoute, openInvoice }) => {
  const tenant = TENANTS.find(t => t.id === tenantId);
  const invoices = INVOICES.filter(i => i.tenantId === tenantId);
  const monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  const totalDue = invoices.filter(i => i.status !== 'paid').reduce((s, i) => s + i.total, 0);
  const paid = invoices.filter(i => i.status === 'paid').reduce((s, i) => s + i.total, 0);

  return (
    <>
      <PageHead title="Invoices"
        subtitle="Monthly invoice covers all your active devices. Tariff at period close."
        actions={<Button icon={<Icon.Download size={14}/>}>Download All</Button>}
      />

      <div className="kpi-row cols-3">
        <KPI label="Outstanding" value={fmtSDG(totalDue)} icon={<Icon.Receipt size={18}/>} tone={totalDue > 0 ? 'amber' : 'green'}
          foot={invoices.filter(i => i.status !== 'paid').length + ' open invoices'} />
        <KPI label="Paid Last 12 Months" value={fmtSDG(paid)} icon={<Icon.Wallet size={18}/>} tone="green"
          foot={invoices.filter(i => i.status === 'paid').length + ' paid'} />
        <KPI label="Active Devices" value={DEVICES.filter(d => d.tenantId === tenantId && d.status !== 'inactive').length}
          icon={<Icon.Cpu size={18}/>} foot="billed this period" />
      </div>

      <Card padded={false}>
        <table className="tbl">
          <thead>
            <tr>
              <th>Invoice</th>
              <th>Period</th>
              <th>Devices</th>
              <th className="num">Total</th>
              <th>Status</th>
              <th>Issued / Due</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {invoices.map(inv => (
              <tr key={inv.id} style={{ cursor: 'pointer' }} onClick={() => openInvoice && openInvoice(inv.id)}>
                <td className="pri mono">{inv.id}</td>
                <td className="mono">{monthNames[inv.month - 1]} {inv.year}</td>
                <td>{inv.devices}</td>
                <td className="num bb">{fmtSDG(inv.total)}</td>
                <td><StatusBadge status={inv.status} /></td>
                <td className="mono meta">
                  <div>{inv.issuedAt}</div>
                  <div style={{ fontSize: 11 }}>due {inv.dueDate}</div>
                </td>
                <td>
                  {inv.status === 'pending_payment' || inv.status === 'overdue'
                    ? <Button size="sm" variant="primary">Pay</Button>
                    : <Button size="sm" variant="ghost" icon={<Icon.Eye size={14}/>}></Button>
                  }
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </>
  );
};

const TenantInvoiceDetail = ({ invoiceId, onClose, onPay }) => {
  const inv = INVOICES.find(i => i.id === invoiceId);
  if (!inv) return null;
  const t = TENANTS.find(x => x.id === inv.tenantId);
  const monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  // Group lines by device
  const lines = inv.lines || [];
  const grouped = {};
  lines.forEach(l => {
    const key = l.group || 'General';
    if (!grouped[key]) grouped[key] = [];
    grouped[key].push(l);
  });

  const showPay = inv.status === 'pending_payment' || inv.status === 'overdue';

  return (
    <Modal
      open={true} onClose={onClose} size="lg"
      title={inv.id}
      subtitle={`${monthNames[inv.month - 1]} ${inv.year} · ${t?.name} · ${inv.devices} devices billed`}
      footer={
        <>
          <Button variant="ghost" icon={<Icon.Download size={14}/>}>Download PDF</Button>
          <div className="spacer"/>
          <Button variant="ghost" onClick={onClose}>Close</Button>
          {showPay && <Button variant="accent" icon={<Icon.Card size={14}/>} onClick={onPay}>Pay {fmtSDG(inv.total)}</Button>}
        </>
      }
    >
      <div className="row" style={{ marginBottom: 18, justifyContent: 'space-between' }}>
        <div>
          <div className="muted" style={{ fontSize: 12 }}>Billed to</div>
          <div className="bb" style={{ fontSize: 15 }}>{t?.name}</div>
          <div className="muted" style={{ fontSize: 12 }}>{t?.address}</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="muted" style={{ fontSize: 12 }}>Amount due</div>
          <div className="mono" style={{ fontSize: 28, fontWeight: 700, color: 'var(--ink-900)' }}>{fmtSDG(inv.total)}</div>
          <StatusBadge status={inv.status} />
        </div>
      </div>

      <div className="row" style={{ marginBottom: 18, padding: 12, background: 'var(--surface)', borderRadius: 8, gap: 24 }}>
        <Meta lbl="Issued" val={inv.issuedAt} />
        <Meta lbl="Due" val={inv.dueDate} />
        <Meta lbl="Tariff" val={inv.tariff.toLocaleString() + ' SDG / kWh'} />
        <Meta lbl="Devices billed" val={inv.devices} />
      </div>

      <div style={{ border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden' }}>
        <div className="invoice-line head">
          <div>Description</div><div className="num">Qty</div><div>Unit</div><div className="num">Unit Price</div><div className="num">Total</div>
        </div>
        {lines.length === 0 && (
          <div style={{ padding: 30, textAlign: 'center', color: 'var(--ink-500)' }}>
            Line items will be available once the invoice is finalized.
          </div>
        )}
        {Object.entries(grouped).map(([group, items], gi) => (
          <React.Fragment key={gi}>
            <div className="invoice-line sub">{group}</div>
            {items.map((l, i) => (
              <div key={i} className="invoice-line">
                <div>{l.desc}</div>
                <div className="num">{typeof l.qty === 'number' ? l.qty.toLocaleString() : l.qty}</div>
                <div className="muted">{l.unit || '—'}</div>
                <div className="num">{l.price ? l.price.toLocaleString() : '0'}</div>
                <div className="num bb">{l.total.toLocaleString()}</div>
              </div>
            ))}
          </React.Fragment>
        ))}
        {lines.length > 0 && (
          <div className="invoice-line total">
            <div>TOTAL</div><div></div><div></div><div></div><div className="num">{inv.total.toLocaleString()} SDG</div>
          </div>
        )}
      </div>
    </Modal>
  );
};

const Meta = ({ lbl, val }) => (
  <div>
    <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.06, color: 'var(--ink-500)' }}>{lbl}</div>
    <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--ink-900)', marginTop: 3 }}>{val}</div>
  </div>
);

// --- Payment modal ---
const PaymentModal = ({ open, onClose, invoice, onSubmit }) => {
  const [method, setMethod] = React.useState('online');
  const [step, setStep] = React.useState('select'); // select | online | upload | success
  const [file, setFile] = React.useState('');
  const [ref, setRef] = React.useState('');

  React.useEffect(() => { if (open) { setStep('select'); setMethod('online'); setFile(''); setRef(''); } }, [open]);

  if (!open || !invoice) return null;

  return (
    <Modal open={open} onClose={onClose}
      title={step === 'success' ? 'Payment received' : 'Pay invoice ' + invoice.id}
      subtitle={step === 'success' ? 'We will notify you when verified' : 'Choose how to settle ' + fmtSDG(invoice.total)}
      footer={
        step === 'select' ? (
          <>
            <Button variant="ghost" onClick={onClose}>Cancel</Button>
            <Button variant="accent" onClick={() => setStep(method)} icon={<Icon.ArrowR size={14}/>}>Continue</Button>
          </>
        ) : step === 'online' ? (
          <>
            <Button variant="ghost" onClick={() => setStep('select')}>Back</Button>
            <Button variant="accent" icon={<Icon.Check size={14}/>} onClick={() => { setStep('success'); onSubmit && onSubmit('online'); }}>
              Pay {fmtSDG(invoice.total)}
            </Button>
          </>
        ) : step === 'upload' ? (
          <>
            <Button variant="ghost" onClick={() => setStep('select')}>Back</Button>
            <Button variant="accent" icon={<Icon.Upload size={14}/>} onClick={() => { setStep('success'); onSubmit && onSubmit('reference_upload'); }}>
              Submit for verification
            </Button>
          </>
        ) : (
          <>
            <Button variant="accent" onClick={onClose}>Done</Button>
          </>
        )
      }
    >
      {step === 'select' && (
        <div className="stack">
          <div className="row" style={{ padding: 14, background: 'var(--surface)', borderRadius: 8, gap: 18 }}>
            <Meta lbl="Invoice" val={invoice.id} />
            <Meta lbl="Amount" val={fmtSDG(invoice.total)} />
            <Meta lbl="Due" val={invoice.dueDate} />
          </div>

          <PayChoice
            on={method === 'online'}
            onSelect={() => setMethod('online')}
            icon={<Icon.Card />}
            title="Pay online with card"
            sub="Visa / Mastercard via Bankak payment gateway · instant confirmation"
            badge="Recommended"
          />
          <PayChoice
            on={method === 'reference_upload'}
            onSelect={() => setMethod('reference_upload')}
            icon={<Icon.Upload />}
            title="Upload bank transfer reference"
            sub="Upload proof of bank transfer. Admin reviews within 1 business day."
          />
        </div>
      )}

      {step === 'online' && (
        <div className="form">
          <Field label="Cardholder name"><input type="text" placeholder="Ahmed Hassan" defaultValue="Ahmed Hassan"/></Field>
          <Field label="Card number"><input type="text" placeholder="4242 4242 4242 4242" defaultValue="4242 4242 4242 4242"/></Field>
          <div className="row-2">
            <Field label="Expiry"><input type="text" placeholder="MM / YY" defaultValue="12 / 28"/></Field>
            <Field label="CVC"><input type="text" placeholder="123" defaultValue="123"/></Field>
          </div>
          <div className="muted" style={{ fontSize: 12, padding: 12, background: 'var(--teal-50)', borderRadius: 8 }}>
            <Icon.Card size={14} style={{ verticalAlign: '-3px', marginRight: 6 }} />
            Test mode — no real charges. Payment will be recorded as <span className="bb mono">paid</span> instantly.
          </div>
        </div>
      )}

      {step === 'upload' && (
        <div className="form">
          <Field label="Bank reference number" required>
            <input type="text" value={ref} onChange={e => setRef(e.target.value)} placeholder="e.g. BNK-2026-0048392" />
          </Field>
          <Field label="Date of transfer" required><input type="date" defaultValue="2026-05-13"/></Field>
          <Field label="Receipt / screenshot" required hint="JPG or PDF up to 10 MB">
            <div style={{
              border: '2px dashed var(--ink-200)', borderRadius: 8, padding: 24, textAlign: 'center',
              cursor: 'pointer', background: file ? 'var(--green-100)' : 'var(--surface)',
            }} onClick={() => setFile('payment-ref-2026-05.pdf')}>
              <Icon.Upload size={22} style={{ color: 'var(--navy-700)' }}/>
              <div className="bb" style={{ marginTop: 8 }}>{file ? file : 'Click to choose file'}</div>
              {file && <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>Uploaded · 248 KB · ready to submit</div>}
            </div>
          </Field>
          <Field label="Notes (optional)"><textarea placeholder="Anything we should know about this payment?"/></Field>
        </div>
      )}

      {step === 'success' && (
        <div style={{ textAlign: 'center', padding: '24px 0' }}>
          <div style={{
            width: 64, height: 64, borderRadius: '50%', background: 'var(--green-100)',
            color: 'var(--green-700)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto'
          }}>
            <Icon.Check size={32}/>
          </div>
          <div style={{ fontSize: 20, fontWeight: 700, marginTop: 18 }}>
            {method === 'online' ? `Payment of ${fmtSDG(invoice.total)} received` : 'Reference uploaded — pending verification'}
          </div>
          <div className="muted" style={{ marginTop: 8, maxWidth: 420, margin: '8px auto 0' }}>
            {method === 'online'
              ? 'Your invoice is now marked as paid. A receipt has been emailed to you.'
              : 'Our team will review and confirm your transfer within 1 business day. You\'ll be notified by email.'}
          </div>
        </div>
      )}
    </Modal>
  );
};

const PayChoice = ({ on, onSelect, icon, title, sub, badge }) => (
  <div onClick={onSelect} style={{
    display: 'flex', gap: 14, padding: 16,
    border: '2px solid ' + (on ? 'var(--navy-700)' : 'var(--line)'),
    background: on ? 'var(--teal-50)' : '#fff',
    borderRadius: 10, cursor: 'pointer',
  }}>
    <div style={{
      width: 40, height: 40, borderRadius: 10, background: '#fff',
      color: on ? 'var(--navy-700)' : 'var(--ink-500)',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      border: '1px solid var(--line)',
    }}>{icon}</div>
    <div style={{ flex: 1 }}>
      <div className="row" style={{ gap: 8 }}>
        <span className="bb">{title}</span>
        {badge && <Badge tone="green">{badge}</Badge>}
      </div>
      <div className="muted" style={{ fontSize: 12.5, marginTop: 3 }}>{sub}</div>
    </div>
    <div style={{
      width: 18, height: 18, borderRadius: '50%',
      border: '2px solid ' + (on ? 'var(--navy-700)' : 'var(--ink-200)'),
      background: on ? 'var(--navy-700)' : '#fff',
      flexShrink: 0,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      color: '#fff',
    }}>{on && <Icon.Check size={12} />}</div>
  </div>
);

// --- Payment history ---
const TenantPayments = ({ tenantId }) => {
  const tenant = TENANTS.find(t => t.id === tenantId);
  const paid = INVOICES.filter(i => i.tenantId === tenantId && i.status === 'paid');
  const monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

  return (
    <>
      <PageHead title="Payment History"
        subtitle={"Every payment made by " + tenant.name}
        actions={<Button icon={<Icon.Download size={14}/>}>Export CSV</Button>}
      />
      <Card padded={false}>
        <table className="tbl">
          <thead>
            <tr><th>Date</th><th>Invoice</th><th>Method</th><th className="num">Amount</th><th>Reference</th><th>Status</th></tr>
          </thead>
          <tbody>
            {paid.map(p => (
              <tr key={p.id}>
                <td className="mono">{p.paidAt}</td>
                <td className="pri mono">{p.id}</td>
                <td>{p.method === 'online' ? <Badge tone="blue"><Icon.Card size={11}/> Card</Badge> : <Badge tone="outline"><Icon.Upload size={11}/> Reference</Badge>}</td>
                <td className="num bb">{fmtSDG(p.total)}</td>
                <td className="meta mono">BNK-2026-{p.id.slice(-3)}</td>
                <td><Badge tone="green" dot>Settled</Badge></td>
              </tr>
            ))}
            {paid.length === 0 && <tr><td colSpan="6" className="muted center" style={{padding:30}}>No payments yet.</td></tr>}
          </tbody>
        </table>
      </Card>
    </>
  );
};

// --- Account ---
const TenantAccount = ({ tenantId }) => {
  const tenant = TENANTS.find(t => t.id === tenantId);
  const [emailNotif, setEmailNotif] = React.useState(true);
  const [smsNotif, setSmsNotif] = React.useState(true);
  const [lowAlerts, setLowAlerts] = React.useState(true);

  return (
    <>
      <PageHead title="My Account"
        subtitle="Profile, password, notification preferences"
      />
      <div className="grid-2">
        <Card title="Profile" action={<Button size="sm" variant="ghost" icon={<Icon.Edit size={14}/>}>Edit</Button>}>
          <div className="row" style={{ alignItems: 'center', marginBottom: 18 }}>
            <div style={{ width: 56, height: 56, borderRadius: '50%',
              background: 'linear-gradient(135deg, var(--navy-700), var(--teal-400))',
              color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 20, fontWeight: 700,
            }}>{tenant.contact.split(' ').map(x => x[0]).join('')}</div>
            <div style={{ marginLeft: 14 }}>
              <div className="bb" style={{ fontSize: 16 }}>{tenant.contact}</div>
              <div className="muted">{tenant.email}</div>
            </div>
          </div>
          <div className="kv">
            <span className="k">Tenant</span><span className="v" style={{fontFamily:'var(--font-sans)'}}>{tenant.name}</span>
            <span className="k">Phone</span><span className="v">{tenant.phone}</span>
            <span className="k">Address</span><span className="v" style={{fontFamily:'var(--font-sans)'}}>{tenant.address}</span>
            <span className="k">Package</span><span className="v" style={{fontFamily:'var(--font-sans)'}}>{tenant.package}</span>
            <span className="k">Member since</span><span className="v">{tenant.joined}</span>
          </div>
        </Card>

        <div className="stack">
          <Card title="Notification preferences">
            <div className="stack" style={{ gap: 14 }}>
              <PrefRow label="Email notifications" sub="Invoice, alarm, payment confirmations"
                on={emailNotif} onChange={setEmailNotif} />
              <PrefRow label="SMS notifications" sub="Critical alarms and outages"
                on={smsNotif} onChange={setSmsNotif} />
              <PrefRow label="Low PAYGo credit alerts" sub="Notify when any device drops below 5 kWh"
                on={lowAlerts} onChange={setLowAlerts} />
            </div>
          </Card>
          <Card title="Security" action={<Button size="sm" variant="ghost">Change password</Button>}>
            <div className="kv">
              <span className="k">Password</span><span className="v" style={{fontFamily:'var(--font-sans)'}}>Last changed 41 days ago</span>
              <span className="k">2FA</span><span className="v" style={{fontFamily:'var(--font-sans)', color:'var(--green-700)'}}>● Enabled (SMS)</span>
              <span className="k">Active sessions</span><span className="v">2 devices</span>
            </div>
          </Card>
        </div>
      </div>
    </>
  );
};

const PrefRow = ({ label, sub, on, onChange }) => (
  <div className="row" style={{ justifyContent: 'space-between', gap: 24, padding: '4px 0' }}>
    <div>
      <div className="bb" style={{ fontSize: 13 }}>{label}</div>
      <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>{sub}</div>
    </div>
    <Toggle on={on} onChange={onChange} />
  </div>
);

Object.assign(window, { TenantInvoices, TenantInvoiceDetail, PaymentModal, TenantPayments, TenantAccount });
