/* Uleez — Écran loueur : mon abonnement & ma facturation
 *
 * Le loueur voyait tout de son activité — réservations, flotte, revenus — mais rien de sa
 * relation COMMERCIALE avec Uleez : quel contrat il a, jusqu'à quand, ce qu'il doit, ce qu'il
 * a déjà réglé, et ce qui se passe s'il ne paie pas. L'endpoint `GET /lessor/billing` existait
 * déjà, aucun écran ne l'appelait.
 *
 * LECTURE SEULE, intégralement. Aucun bouton n'écrit : le loueur consulte son contrat,
 * télécharge ses factures, et voit où il en est. Toute action sur la facturation appartient à
 * l'admin, et le backend n'expose d'ailleurs aucun verbe d'écriture sur ce chemin.
 *
 * Fichier séparé : lessor3.jsx dépasse déjà 90 Ko.
 */
const { useState: useL4, useEffect: useLE4 } = React;

// Comme partout ailleurs, `label` porte une CLÉ : ces tables sont des constantes de module,
// évaluées au chargement, alors que la langue change sans rechargement.
const L4_SUB_STATUS = {
  trial:     { label: 'bill.sub.trial',     cls: 'blue' },
  active:    { label: 'bill.sub.active',    cls: 'green' },
  past_due:  { label: 'bill.sub.past_due',  cls: 'amber' },
  suspended: { label: 'bill.sub.suspended', cls: 'red' },
  cancelled: { label: 'bill.sub.cancelled', cls: 'gray' },
  expired:   { label: 'bill.sub.expired',   cls: 'gray' },
};

const L4_INVOICE_STATUS = {
  draft:          { label: 'bill.inv.draft',          cls: 'gray' },
  issued:         { label: 'bill.inv.issued',         cls: 'blue' },
  sent:           { label: 'bill.inv.sent',           cls: 'blue' },
  partially_paid: { label: 'bill.inv.partially_paid', cls: 'amber' },
  paid:           { label: 'bill.inv.paid',           cls: 'green' },
  overdue:        { label: 'bill.inv.overdue',        cls: 'red' },
  void:           { label: 'bill.inv.void',           cls: 'gray' },
};

/** Date longue dans la langue COURANTE — `'fr-FR'` était codé en dur. */
const l4Date = (d) => {
  if (!d) return '—';
  const lang = window.I18N ? I18N.lang : 'fr';
  const locale = lang === 'ar' ? 'ar-DZ' : lang === 'en' ? 'en-GB' : 'fr-FR';
  return new Date(d).toLocaleDateString(locale, { day: 'numeric', month: 'long', year: 'numeric' });
};

/** Date courte dans la langue courante. */
const l4ShortDate = (d) => {
  if (!d) return '—';
  const lang = window.I18N ? I18N.lang : 'fr';
  return new Date(d).toLocaleDateString(lang === 'ar' ? 'ar-DZ' : lang === 'en' ? 'en-GB' : 'fr-FR');
};

function LessorBilling({ navigate }) {
  const t = window.I18N ? I18N.useT() : ((k) => k);
  const toast = useToast();
  const [data, setData] = useL4(null);
  const [loading, setLoading] = useL4(true);
  const [err, setErr] = useL4(false);
  const [kind, setKind] = useL4('');
  // Pour préremplir le mail de contact plus bas — best-effort et indépendant du reste de
  // l'écran : son échec ne doit ni bloquer l'affichage de la facturation, ni empêcher le
  // bouton de contact de fonctionner (il retombe alors sur un mail sans info préremplie).
  const [profile, setProfile] = useL4(null);

  const load = () => {
    setLoading(true);
    setErr(false);
    API.lessor.getBilling()
      .then(setData)
      .catch(() => setErr(true))
      .finally(() => setLoading(false));
  };

  useLE4(() => { load(); }, []);
  useLE4(() => { API.lessor.getProfile().then(setProfile).catch(() => {}); }, []);

  // Mail préformaté : nom d'agence, téléphone et email déjà dedans, avec une ligne à compléter
  // pour la raison du message — évite au loueur de ressaisir ses coordonnées, sans lui imposer
  // un texte figé (tout reste modifiable dans son client mail avant l'envoi).
  const supportMailto = () => {
    const agency = (profile && (profile.businessName || profile.agencyName)) || '';
    const phone = (profile && profile.phone) || '';
    const email = (profile && profile.email) || '';
    const body = [
      t('bill.mailGreeting'),
      '',
      t('bill.mailReasonPlaceholder'),
      '',
      '',
      '——',
      t('bill.mailInfoHeader'),
      `${t('bill.mailAgencyLabel')} ${agency || '—'}`,
      `${t('bill.mailPhoneLabel')} ${phone || '—'}`,
      `${t('bill.mailEmailLabel')} ${email || '—'}`,
    ].join('\n');
    const subject = t('bill.mailSubject', { agency: agency || t('bill.mailSubjectFallback') });
    return `mailto:support@uleez.com?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
  };

  const download = (inv) =>
    API.lessor.downloadInvoice(inv.id, inv.reference)
      .catch(() => toast({ variant: 'error', title: t('bill.downloadFailed') }));

  if (loading) {
    return (
      <div className="page-wide">
        <Sk w="100%" h={150} r={16} />
        <div style={{ height: 16 }} />
        <Sk w="100%" h={220} r={16} />
      </div>
    );
  }

  if (err || !data) {
    return (
      <div className="page-wide">
        <Card><div className="card-pad">
          <EmptyState variant="err" title={t('bill.loadFailed')}
            action={<Button variant="secondary" icon="refresh" onClick={load}>{t('common.retry')}</Button>} />
        </div></Card>
      </div>
    );
  }

  const sub = data.subscription;
  const compliance = data.compliance || {};
  const roi = data.roi || {};
  const invoices = (data.invoices || []).filter(i => !kind || i.kind === kind);

  return (
    <div className="page-wide">
      {/* ── L'alerte d'abord, quand elle existe ────────────────────────────────
          Un loueur en retard doit lire CE QUI VA SE PASSER et QUAND avant tout le reste.
          Enfoui plus bas, l'avertissement arriverait après la coupure. */}
      {data.suspensionAt && (
        <div className="banner-warn" style={{ marginBottom: 16 }}>
          <strong>{t('bill.overdueTitle')}</strong>{' '}
          {t('bill.overdueBody', { date: l4Date(data.suspensionAt), days: data.graceDays })}
        </div>
      )}

      {data.outstanding > 0 && !data.suspensionAt && (
        <div className="banner-info" style={{ marginBottom: 16 }}>
          <strong>{t('bill.outstandingTitle', { amount: KD.fmtDA(data.outstanding) })}</strong>{' '}
          {t('bill.outstandingBody')}
        </div>
      )}

      {/* ── Mon contrat ───────────────────────────────────────────────────── */}
      <Card style={{ marginBottom: 18 }}>
        <CardHead title={t('bill.contractTitle')}
          sub={t('bill.contractSub')}
          icon={{ name: 'building', color: 'violet' }}
          right={sub ? <StatusBadge map={L4_SUB_STATUS} value={sub.status} /> : null} />
        <div className="card-pad">
          {!sub ? (
            <EmptyState variant="empty" icon="building"
              title={t('bill.noSubTitle')}
              desc={t('bill.noSubDesc')} />
          ) : (
            <>
              <div className="stat-grid">
                <div className="statcard" style={{ borderLeft: '3px solid #7c3aed' }}>
                  <div className="muted" style={{ fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.5px' }}>{t('bill.formula')}</div>
                  <div style={{ fontSize: 22, fontWeight: 800, marginTop: 6 }}>{t(`bill.plan.${sub.plan}`)}</div>
                  <div className="muted" style={{ fontSize: 11.5, marginTop: 4 }}>
                    {KD.fmtDA(sub.priceAmount)} {t(`bill.per.${sub.plan}`)}
                  </div>
                </div>

                <div className="statcard" style={{ borderLeft: '3px solid #0284c7' }}>
                  <div className="muted" style={{ fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.5px' }}>{t('bill.nextDue')}</div>
                  <div style={{ fontSize: 18, fontWeight: 800, marginTop: 8 }}>{l4Date(sub.currentPeriodEnd)}</div>
                  <div className="muted" style={{ fontSize: 11.5, marginTop: 4 }}>
                    {sub.daysToExpiry == null ? '—'
                      : sub.daysToExpiry >= 0 ? t('bill.inDays', { n: sub.daysToExpiry })
                        : t('bill.overdueDays', { n: Math.abs(sub.daysToExpiry) })}
                    {sub.autoRenew ? t('bill.autoRenew') : t('bill.noRenew')}
                  </div>
                </div>

                <div className="statcard" style={{ borderLeft: `3px solid ${compliance.ok ? '#059669' : '#e11d48'}` }}>
                  <div className="muted" style={{ fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.5px' }}>{t('bill.situation')}</div>
                  <div style={{ fontSize: 18, fontWeight: 800, marginTop: 8, color: compliance.ok ? '#059669' : '#e11d48' }}>
                    {compliance.ok ? t('bill.compliant') : (compliance.label || t('bill.toSettle'))}
                  </div>
                  <div className="muted" style={{ fontSize: 11.5, marginTop: 4 }}>
                    {data.outstanding > 0 ? t('bill.pendingAmount', { amount: KD.fmtDA(data.outstanding) }) : t('bill.nothingDue')}
                  </div>
                </div>
              </div>

              {/* La période de bienvenue explique à elle seule pourquoi aucune facture
                  n'apparaît. Sans cette mention, une liste vide passe pour une anomalie. */}
              {sub.inTrial && (
                <div className="banner-info" style={{ marginTop: 14 }}>
                  <strong>{sub.trialEndsAt
                    ? t('bill.trialUntil', { date: l4Date(sub.trialEndsAt) })
                    : t('bill.trialOngoing')}</strong>{' '}
                  {t('bill.trialNote')}
                </div>
              )}
            </>
          )}
        </div>
      </Card>

      {/* ── Ce que la plateforme rapporte, face à ce qu'elle coûte ──────────
          Le chiffre que Ramzy veut pouvoir montrer à un loueur hésitant. Il est calculé sur
          les 12 derniers mois, à partir des locations RÉELLEMENT ENCAISSÉES — la même base
          que l'écran Paiements, donc réconciliable ligne à ligne.

          La commission est volontairement absente du « coût » : elle est proportionnelle au
          chiffre d'affaires et déjà déduite du net perçu. L'ajouter la compterait deux fois. */}
      {roi.subscriptionBilled > 0 && (
        <Card style={{ marginBottom: 18 }}>
          <CardHead title={t('bill.roiTitle')} sub={t('bill.roiSub')}
            icon={{ name: 'trendUp', color: 'green' }} />
          <div className="card-pad">
            <div className="grid-2" style={{ gridTemplateColumns: 'repeat(auto-fit,minmax(190px,1fr))', gap: 12 }}>
              {/* `.roi-tile` et non `.kv` : `.kv` est une ligne clé-valeur en `display:flex`
                  direction row, qui posait ces trois blocs côte à côte au lieu de les empiler
                  — d'où le décalage entre « Locations encaissées », le montant et le décompte. */}
              <div className="roi-tile">
                <div className="muted roi-label">{t('bill.roiEarned')}</div>
                <div className="roi-value" style={{ color: '#059669' }}>{KD.fmtDA(roi.rentalEarned)}</div>
                <div className="muted roi-hint">{t('bill.roiBookings', { n: roi.bookings })}</div>
              </div>
              <div className="roi-tile">
                <div className="muted roi-label">{t('bill.roiBilled')}</div>
                <div className="roi-value" style={{ color: '#7c3aed' }}>{KD.fmtDA(roi.subscriptionBilled)}</div>
                <div className="muted roi-hint">{t('bill.roiPaid', { amount: KD.fmtDA(roi.subscriptionPaid) })}</div>
              </div>
              {roi.ratio != null && (
                <div className="roi-tile" style={{ background: 'var(--brand-50)' }}>
                  <div className="muted roi-label">{t('bill.roiRatio')}</div>
                  <div className="roi-value" style={{ color: 'var(--brand-700)' }}>× {roi.ratio}</div>
                  <div className="muted roi-hint">{t('bill.roiPerDA')}</div>
                </div>
              )}
            </div>
            <div className="muted" style={{ fontSize: 11, marginTop: 10, lineHeight: 1.5 }}>
              {t('bill.roiNote')}
            </div>
          </div>
        </Card>
      )}

      {/* ── Mes factures ──────────────────────────────────────────────────── */}
      <Card style={{ marginBottom: 18 }}>
        <CardHead title={t('bill.invoicesTitle')} sub={t('bill.invoicesSub')}
          icon={{ name: 'wallet', color: 'blue' }}
          right={<Button size="sm" variant="secondary" icon="refresh" onClick={load}>{t('common.refresh')}</Button>} />

        <div className="toolbar" style={{ padding: '12px 14px', borderBottom: '1px solid var(--line)' }}>
          <Select value={kind} onChange={e => setKind(e.target.value)} style={{ width: 'auto' }}>
            <option value="">{t('bill.allKinds')}</option>
            <option value="commission">{t('bill.kind.commission')}</option>
            <option value="subscription">{t('bill.kind.subscription')}</option>
          </Select>
        </div>

        {invoices.length === 0 ? (
          <EmptyState variant="empty" icon="wallet" title={t('bill.noInvoices')}
            desc={t('bill.noInvoicesDesc')} />
        ) : (
          <div className="tbl-wrap"><table className="tbl">
            <thead><tr>
              <th>{t('bill.colRef')}</th><th>{t('bill.colKind')}</th><th>{t('bill.colPeriod')}</th><th>{t('bill.colDue')}</th>
              <th style={{ textAlign: 'right' }}>{t('bill.colAmount')}</th>
              <th style={{ textAlign: 'right' }}>{t('bill.colRemaining')}</th>
              <th>{t('bill.colStatus')}</th>
              <th style={{ textAlign: 'right' }}>PDF</th>
            </tr></thead>
            <tbody>
              {invoices.map(inv => (
                <tr key={inv.id}>
                  <td className="mono strong">{inv.reference}</td>
                  <td>{t(`bill.kind.${inv.kind}`)}</td>
                  <td className="nowrap">{inv.periodLabel}</td>
                  <td className="nowrap">
                    <div className="cellstack">
                      <div>{l4ShortDate(inv.dueAt)}</div>
                      {inv.isOverdue && (
                        <div className="sub" style={{ color: 'var(--rose-600, #e11d48)' }}>
                          {t('bill.daysLate', { n: inv.daysOverdue })}
                        </div>
                      )}
                    </div>
                  </td>
                  <td className="cellnum" style={{ textAlign: 'right' }}>{KD.fmtDA(inv.amountDue)}</td>
                  <td className="cellnum" style={{ textAlign: 'right', fontWeight: 800 }}>
                    {inv.remaining > 0 ? KD.fmtDA(inv.remaining) : '—'}
                  </td>
                  <td><StatusBadge map={L4_INVOICE_STATUS} value={inv.status} /></td>
                  <td style={{ textAlign: 'right' }}>
                    <Button size="sm" variant="secondary" icon="download" onClick={() => download(inv)}>
                      {t('common.download')}
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table></div>
        )}
      </Card>

      {/* ── Comment régler ────────────────────────────────────────────────── */}
      <Card>
        <CardHead title={t('bill.howToPayTitle')} sub={t('bill.howToPaySub')} icon={{ name: 'info', color: 'blue' }} />
        <div className="card-pad">
          <div style={{ fontSize: 13.5, lineHeight: 1.7 }}>
            {t('bill.howToPayBody1')}
            <br /><br />
            {t('bill.howToPayBody2')}
          </div>
          <div style={{ marginTop: 14 }}>
            {/* L'écran Assistance loueur a été retiré du back-office web (0.9.6) — les urgences
                client se gèrent désormais uniquement côté mobile. Ce bouton n'a jamais eu de
                rapport avec les urgences SOS (question générale de facturation) : un mailto
                suffit, pas besoin d'un écran dédié — préformaté (voir supportMailto) pour éviter
                au loueur de ressaisir ses coordonnées à chaque fois. */}
            <Button variant="secondary" icon="lifebuoy" onClick={() => { window.location.href = supportMailto(); }}>
              {t('bill.contactSupport')}
            </Button>
          </div>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { LessorBilling });
