const { useState, useEffect } = React;

function BonPreview() {
  const { navigate, t, navParams, refreshBons } = window.useApp();
  const [bon, setBon] = useState(null);
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    if (navParams?.bon) {
      setBon(navParams.bon);
      setSaved(false);
    } else if (navParams?.bonId) {
      setBon(storage.getBon(navParams.bonId));
      setSaved(true);
    }
  }, [navParams]);

  if (!bon) return null;

  const p = bon.profile || {};
  const fmtDateTime = (date, time) => {
    if (!date) return '—';
    const d = new Date(date + (time ? `T${time}` : ''));
    return d.toLocaleDateString('fr-FR', { day: '2-digit', month: 'long', year: 'numeric' }) + (time ? ` à ${time}` : '');
  };
  const fmtPrice = (v) => v ? `${parseFloat(v).toLocaleString('fr-FR', { minimumFractionDigits: 2 })} €` : '—';

  const handleSaveAndPrint = () => {
    if (!saved) {
      storage.saveBon(bon);
      refreshBons();
      setSaved(true);
    }
    window.printBon(bon);
  };

  const handleSave = () => {
    storage.saveBon(bon);
    refreshBons();
    setSaved(true);
  };

  const handleDelete = () => {
    if (window.confirm(t('confirmDelete'))) {
      storage.deleteBon(bon.id);
      refreshBons();
      navigate('history');
    }
  };

  return (
    <div style={pv.screen}>
      {/* Header */}
      <div style={pv.header}>
        <button style={pv.backBtn} onClick={() => navigate(saved ? 'history' : 'new')}>
          <ChevLeft /> {t('back')}
        </button>
        <span style={pv.headerTitle}>{t('bonDetail')}</span>
        {saved && (
          <button style={pv.deleteBtn} onClick={handleDelete}>🗑</button>
        )}
        {!saved && <div style={{ width: 44 }}></div>}
      </div>

      <div style={pv.body}>
        {/* The bon document */}
        <div id="bon-document" style={pv.doc}>
          {/* Doc header */}
          <div style={pv.docHeader}>
            <div style={{ flex: 1 }}>
              <div style={pv.companyName}>{p.companyName || '—'}</div>
              {p.address && <div style={pv.companyDetail}>{p.address}</div>}
              {p.siret && <div style={pv.companyDetail}>SIRET : {p.siret}</div>}
              {p.evtc && <div style={pv.companyDetail}>EVTC : {p.evtc}</div>}
            </div>
            <div style={pv.logoBox}>
              {p.logo
                ? <img src={p.logo} alt="logo" style={{ width: '100%', height: '100%', objectFit: 'contain', borderRadius: 6 }} />
                : <span style={{ fontSize: 10, color: 'var(--text-3)' }}>LOGO</span>
              }
            </div>
          </div>

          {/* Title bar */}
          <div style={pv.titleBar}>
            <span>{t('orderForm')}</span>
            <span style={{ fontSize: 13, opacity: 0.85 }}>{bon.id}</span>
          </div>

          {/* Client */}
          <DocSection>
            <DocRow label="Client" value={bon.clientName || '—'} bold />
            {bon.clientPhone && <DocRow label="Tél." value={bon.clientPhone} />}
          </DocSection>

          {/* Dates */}
          <DocSection>
            <DocRow label={t('reservedOn')} value={fmtDateTime(bon.reservationDate, bon.reservationTime)} />
            <DocRow label={t('pickupOn')} value={fmtDateTime(bon.pickupDate, bon.pickupTime)} bold />
          </DocSection>

          {/* Addresses */}
          <DocSection>
            <DocRow label={t('from')} value={bon.pickupAddress || '—'} />
            <DocRow label={t('to')} value={bon.dropoffAddress || '—'} />
          </DocSection>

          {/* Vehicle */}
          <DocSection>
            {bon.plate && <DocRow label={t('plate')} value={bon.plate} />}
            {bon.passengers && <DocRow label={t('passengers')} value={bon.passengers} />}
          </DocSection>

          {/* Price */}
          <div style={pv.priceSection}>
            {bon.priceHT && (
              <div style={pv.priceRow}>
                <span style={pv.priceLabel}>Prix HT</span>
                <span style={pv.priceValue}>{fmtPrice(bon.priceHT)}</span>
              </div>
            )}
            <div style={{ ...pv.priceRow, ...pv.priceTotalRow }}>
              <span style={pv.priceTotalLabel}>Total TTC</span>
              <span style={pv.priceTotalValue}>{fmtPrice(bon.priceTTC)}</span>
            </div>
            <div style={pv.vatNote}>{t('vatNote')}</div>
          </div>
        </div>

      </div>

      {/* Bottom bar */}
      <div style={pv.bottomBar}>
        <button style={pv.editBtn} onClick={() => navigate(saved ? 'history' : 'new')}>
          ← {saved ? t('history') : t('edit')}
        </button>
        {!saved && (
          <button style={pv.saveBtn} onClick={handleSave}>
            💾 {t('save')}
          </button>
        )}
        <button style={pv.pdfBtn} onClick={handleSaveAndPrint}>
          ⬇ PDF
        </button>
      </div>
    </div>
  );
}

function DocSection({ children }) {
  return <div style={pv.docSection}>{children}</div>;
}

function DocRow({ label, value, bold }) {
  return (
    <div style={pv.docRow}>
      <span style={pv.docLabel}>{label}</span>
      <span style={{ ...pv.docValue, ...(bold ? { fontWeight: 700, color: 'var(--text)' } : {}) }}>{value}</span>
    </div>
  );
}

function ChevLeft() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ verticalAlign: 'middle' }}>
      <polyline points="15 18 9 12 15 6"/>
    </svg>
  );
}

const pv = {
  screen: { display: 'flex', flexDirection: 'column', height: '100%', background: 'var(--bg)' },
  header: {
    background: 'var(--surface)', borderBottom: '1px solid var(--border)',
    padding: '0 16px', height: 56, paddingTop: 'var(--safe-top)',
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    flexShrink: 0,
  },
  headerTitle: { fontSize: 16, fontWeight: 700, color: 'var(--text)' },
  backBtn: { background: 'none', border: 'none', color: 'var(--text-2)', fontSize: 14, fontFamily: 'var(--font)', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 2, width: 70 },
  deleteBtn: { background: 'none', border: 'none', fontSize: 20, cursor: 'pointer', width: 44, display: 'flex', alignItems: 'center', justifyContent: 'flex-end' },
  body: { flex: 1, overflowY: 'auto', padding: 16, paddingBottom: 16, display: 'flex', flexDirection: 'column', gap: 12 },

  // Document styles
  doc: { background: 'var(--surface)', borderRadius: 'var(--radius)', border: '1px solid var(--border)', boxShadow: 'var(--shadow-md)' },
  docHeader: { padding: '16px 16px 12px', display: 'flex', gap: 12, alignItems: 'flex-start', borderBottom: '2px solid var(--dark)' },
  companyName: { fontSize: 16, fontWeight: 800, color: 'var(--text)', letterSpacing: '-0.3px' },
  companyDetail: { fontSize: 11.5, color: 'var(--text-2)', marginTop: 2 },
  logoBox: { width: 56, height: 56, border: '1.5px dashed var(--border)', borderRadius: 8, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--surface-2)' },
  titleBar: { background: 'var(--dark)', color: '#fff', padding: '8px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 14, fontWeight: 800, letterSpacing: '0.5px' },
  docSection: { padding: '10px 16px', borderBottom: '1px solid var(--border)', display: 'flex', flexDirection: 'column', gap: 5 },
  docRow: { display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 },
  docLabel: { fontSize: 12, color: 'var(--text-3)', flexShrink: 0 },
  docValue: { fontSize: 13.5, color: 'var(--text-2)', textAlign: 'right' },
  priceSection: { padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 6 },
  priceRow: { display: 'flex', justifyContent: 'space-between', alignItems: 'center' },
  priceLabel: { fontSize: 13, color: 'var(--text-2)' },
  priceValue: { fontSize: 14, color: 'var(--text)', fontWeight: 500 },
  priceTotalRow: { borderTop: '1.5px solid var(--dark)', paddingTop: 8, marginTop: 2 },
  priceTotalLabel: { fontSize: 15, fontWeight: 800, color: 'var(--text)' },
  priceTotalValue: { fontSize: 18, fontWeight: 800, color: 'var(--text)' },
  vatNote: { fontSize: 11, color: 'var(--text-3)', textAlign: 'center', marginTop: 4 },

  saveBtn: { background: 'var(--gold-light)', color: 'var(--gold-dark)', border: '1px solid var(--gold)', borderRadius: 'var(--radius)', padding: '12px', fontSize: 14, fontWeight: 700, fontFamily: 'var(--font)', cursor: 'pointer', width: '100%' },
  bottomBar: { padding: '12px 16px', paddingBottom: 'calc(12px + var(--safe-bottom))', background: 'var(--surface)', borderTop: '1px solid var(--border)', display: 'flex', gap: 8, flexShrink: 0 },
  editBtn: { flex: 1, background: 'var(--surface-2)', color: 'var(--text)', border: '1px solid var(--border)', borderRadius: 'var(--radius)', padding: '12px 8px', fontSize: 14, fontWeight: 600, fontFamily: 'var(--font)', cursor: 'pointer' },
  saveBtn: { flex: 1, background: 'var(--gold-light)', color: 'var(--gold-dark)', border: '1px solid var(--gold)', borderRadius: 'var(--radius)', padding: '12px 8px', fontSize: 14, fontWeight: 700, fontFamily: 'var(--font)', cursor: 'pointer' },
  pdfBtn: { flex: 1, background: 'var(--gold)', color: '#fff', border: 'none', borderRadius: 'var(--radius)', padding: '12px 8px', fontSize: 14, fontWeight: 700, fontFamily: 'var(--font)', cursor: 'pointer' },
};

Object.assign(window, { BonPreview });
