/* global React, Icon, Badge, Tag, Avatar, Button, Field, Toggle, Tabs, Segmented, PeriodPicker, Card, Metric, Modal, Pager, toast */

var { useState: useState_mk } = React;

// ============================================================
// PAGE: MARKUPS — our profit control over vendor NET rates
// 3 tiers, default for auto-activated agencies, per-agency/group overrides
// ============================================================

const SEGMENTS = [
  { key: "hotel", label: "Accommodation", tag: "hotel" },
  { key: "car", label: "Car Rental", tag: "rental" },
  { key: "transfer", label: "Transfer", tag: "transfer" },
  { key: "lounge", label: "Airport Lounge", tag: "vip" },
  { key: "vipair", label: "VIP Airport", tag: "vipas" },
  { key: "tour", label: "Private Tours", tag: "ptour" },
];

// Default tier markups (% added on top of vendor NET rate)
const DEFAULT_TIERS = {
  Silver: { hotel: 12, car: 9, transfer: 14, lounge: 15, vipair: 16, tour: 13 },
  Gold:   { hotel: 9,  car: 7, transfer: 11, lounge: 12, vipair: 13, tour: 10 },
  Unique: { hotel: 6,  car: 5, transfer: 8,  lounge: 9,  vipair: 10, tour: 7 },
};

function PageMarkups() {
  const [tab, setTab] = useState_mk("tiers");
  const [agencyCount, setAgencyCount] = useState_mk((window.MOCK && window.MOCK.TRAVEL_AGENCIES && window.MOCK.TRAVEL_AGENCIES.length) || 0);
  const [groupCount, setGroupCount] = useState_mk((window.MOCK && window.MOCK.TRAVEL_GROUPS && window.MOCK.TRAVEL_GROUPS.length) || 0);
  React.useEffect(() => {
    if (!window.TrekkoAPI) return;
    window.TrekkoAPI.getAgencies().then((r) => { if (r) setAgencyCount(r.length); });
    window.TrekkoAPI.getTravelGroups().then((r) => { if (r) setGroupCount(r.length); });
  }, []);
  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-head__title">Markups</h1>
          <div className="page-head__sub">Our profit control — markup added on top of vendor NET rates, per service segment. Three tiers; new agencies start on the default tier and can be adjusted individually.</div>
        </div>
        <div className="page-head__actions">
          <Button kind="secondary" icon={<Icon.Download />}>Export</Button>
        </div>
      </div>

      <div className="row" style={{ gap: 10, marginBottom: 18, background: "var(--info-bg)", padding: "10px 12px", borderRadius: 8, color: "var(--info)" }}>
        <Icon.Info stroke="currentColor" />
        <div style={{ fontSize: 13 }}>Vendors always provide <b>NET rates</b>. The markup % below is what we add to set the <b>sell price</b> to travel agencies — this is where we control our margin.</div>
      </div>

      <Tabs active={tab} onChange={setTab} tabs={[
        { id: "tiers", label: "Markup tiers" },
        { id: "agencies", label: "By travel agency", count: agencyCount },
        { id: "groups", label: "By travel group", count: groupCount },
      ]} />

      {tab === "tiers" && <MarkupTiers />}
      {tab === "agencies" && <MarkupByAgency />}
      {tab === "groups" && <MarkupByGroup />}
    </div>
  );
}

function MarkupTiers() {
  const [tiers, setTiers] = useState_mk(DEFAULT_TIERS);
  const [defaultTier, setDefaultTier] = useState_mk("Silver");
  const [editing, setEditing] = useState_mk(false);

  const setVal = (tier, seg, val) => setTiers((t) => ({ ...t, [tier]: { ...t[tier], [seg]: val } }));

  return (
    <>
      <div className="grid grid--3" style={{ gap: 14, marginBottom: 18 }}>
        {["Silver", "Gold", "Unique"].map((tier) => {
          const avg = (SEGMENTS.reduce((s, seg) => s + tiers[tier][seg.key], 0) / SEGMENTS.length).toFixed(1);
          const isDefault = defaultTier === tier;
          return (
            <div key={tier} className="metric" style={{ borderTop: `3px solid ${tier === "Unique" ? "#635bff" : tier === "Gold" ? "#e0b341" : "#8898aa"}` }}>
              <div className="metric__label" style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span>{tier === "Unique" ? <Badge tone="indigo">{tier}</Badge> : tier === "Gold" ? <Badge tone="warning">{tier}</Badge> : <Badge tone="neutral">{tier}</Badge>}</span>
                {isDefault ? <Badge tone="success">Default</Badge> : <button className="btn btn--ghost btn--sm" onClick={() => { setDefaultTier(tier); toast({ title: `${tier} set as default tier`, tone: "success" }); }}>Set default</button>}
              </div>
              <div className="metric__value">{avg}%</div>
              <div className="tiny muted">Average markup across segments</div>
            </div>
          );
        })}
      </div>

      <Card title="Tier markup matrix" sub="Markup % added on vendor NET rate, per segment"
        actions={editing
          ? <><Button kind="ghost" size="sm" onClick={() => { setTiers(DEFAULT_TIERS); setEditing(false); }}>Reset</Button><Button kind="primary" size="sm" icon={<Icon.Check />} onClick={() => { setEditing(false); toast({ title: "Markup tiers saved", tone: "success" }); }}>Save</Button></>
          : <Button kind="secondary" size="sm" icon={<Icon.Edit />} onClick={() => setEditing(true)}>Edit tiers</Button>}
        flush>
        <table className="tbl">
          <thead>
            <tr><th>Service segment</th><th className="num">Silver (base)</th><th className="num">Gold</th><th className="num">Unique (best)</th></tr>
          </thead>
          <tbody>
            {SEGMENTS.map((seg) => (
              <tr key={seg.key}>
                <td><Tag kind={seg.tag}>{seg.label}</Tag></td>
                {["Silver", "Gold", "Unique"].map((tier) => (
                  <td key={tier} className="num">
                    {editing
                      ? <input className="input" type="number" value={tiers[tier][seg.key]} onChange={(e) => setVal(tier, seg.key, +e.target.value)} style={{ width: 80, height: 30, marginLeft: "auto" }} />
                      : <span className="mono bold">{tiers[tier][seg.key]}%</span>}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <div style={{ height: 18 }} />
      <Card title="How it works" flush>
        <div style={{ padding: 18, display: "grid", gap: 10, fontSize: 13, color: "var(--ink-2)" }}>
          <div className="row" style={{ gap: 10 }}><span style={{ width: 22, height: 22, borderRadius: 999, background: "var(--indigo-50)", color: "var(--indigo)", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 700, flexShrink: 0 }}>1</span> A vendor returns a NET rate (e.g. a hotel night at <b>€100</b>).</div>
          <div className="row" style={{ gap: 10 }}><span style={{ width: 22, height: 22, borderRadius: 999, background: "var(--indigo-50)", color: "var(--indigo)", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 700, flexShrink: 0 }}>2</span> The agency's tier markup is applied (Silver Accommodation = <b>+12%</b>).</div>
          <div className="row" style={{ gap: 10 }}><span style={{ width: 22, height: 22, borderRadius: 999, background: "var(--indigo-50)", color: "var(--indigo)", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 700, flexShrink: 0 }}>3</span> Sell price = NET / (1 - markup) = €100 / (1 - 0.12) = <b>€113.64</b>. Our profit = <b>€13.64</b>.</div>
          <div className="row" style={{ gap: 10 }}><span style={{ width: 22, height: 22, borderRadius: 999, background: "var(--success-bg)", color: "var(--success)", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 700, flexShrink: 0 }}>4</span> New auto-activated agencies start on the <b>{defaultTier}</b> default tier; adjust per agency anytime.</div>
        </div>
      </Card>
    </>
  );
}

function MarkupByAgency() {
  const [q, setQ] = useState_mk("");
  const [page, setPage] = useState_mk(1);
  const [edit, setEdit] = useState_mk(null);
  const [agencies, setAgencies] = useState_mk((window.MOCK && window.MOCK.TRAVEL_AGENCIES) || []);
  React.useEffect(() => {
    if (!window.TrekkoAPI) return;
    window.TrekkoAPI.getAgencies().then((rows) => { if (rows && rows.length) setAgencies(rows); });
  }, []);
  const PAGE = 30;
  const rows = agencies.filter((a) => !q || (a.name + a.country).toLowerCase().includes(q.toLowerCase()));
  const slice = rows.slice((page - 1) * PAGE, page * PAGE);

  return (
    <>
      <div className="filter-bar">
        <input className="input input--search" placeholder="Search agency…" style={{ width: 280 }} value={q} onChange={(e) => setQ(e.target.value)} />
        <select className="select"><option>All tiers</option><option>Silver</option><option>Gold</option><option>Unique</option></select>
        <select className="select"><option>All markets</option><option>Iberia</option><option>DACH</option><option>UK</option></select>
        <span className="spacer" />
        <span className="tiny muted">Override the tier markup per agency · per segment</span>
      </div>
      <div className="tbl-wrap tbl-wrap--linked">
        <table className="tbl">
          <thead>
            <tr>
              <th>Agency</th><th>Tier</th>
              {SEGMENTS.map((s) => <th key={s.key} className="num">{s.label.split(" ")[0]}</th>)}
              <th className="col-actions"></th>
            </tr>
          </thead>
          <tbody>
            {slice.map((a) => {
              const tier = a.markup === "Unique" ? "Unique" : a.markup === "Gold" ? "Gold" : "Silver";
              const m = DEFAULT_TIERS[tier];
              return (
                <tr key={a.id}>
                  <td><span className="user-cell"><Avatar name={a.name} size="sm" /><span><div className="bold">{a.name}</div><div className="tiny muted">{a.country}</div></span></span></td>
                  <td>{tier === "Unique" ? <Badge tone="indigo">Unique</Badge> : tier === "Gold" ? <Badge tone="warning">Gold</Badge> : <Badge tone="neutral">Silver</Badge>}</td>
                  {SEGMENTS.map((s) => <td key={s.key} className="num mono">{m[s.key]}%</td>)}
                  <td className="col-actions"><Button kind="secondary" size="sm" icon={<Icon.Edit />} onClick={() => setEdit(a)}>Adjust</Button></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      <Pager page={page} pageSize={PAGE} total={rows.length} onPage={setPage} />
      <AdjustMarkupModal entity={edit} kind="agency" onClose={() => setEdit(null)} />
    </>
  );
}

function MarkupByGroup() {
  const [edit, setEdit] = useState_mk(null);
  const [groups, setGroups] = useState_mk((window.MOCK && window.MOCK.TRAVEL_GROUPS) || []);
  React.useEffect(() => {
    if (!window.TrekkoAPI) return;
    window.TrekkoAPI.getTravelGroups().then((rows) => { if (rows && rows.length) setGroups(rows); });
  }, []);
  return (
    <>
      <div className="filter-bar">
        <input className="input input--search" placeholder="Search travel group…" style={{ width: 280 }} />
        <span className="spacer" />
        <span className="tiny muted">A group markup applies to all its member agencies unless individually overridden</span>
      </div>
      <div className="tbl-wrap tbl-wrap--linked">
        <table className="tbl">
          <thead>
            <tr>
              <th>Travel group</th><th>Tier</th><th className="num">Agencies</th>
              {SEGMENTS.map((s) => <th key={s.key} className="num">{s.label.split(" ")[0]}</th>)}
              <th className="col-actions"></th>
            </tr>
          </thead>
          <tbody>
            {groups.map((g, i) => {
              const tier = ["Silver", "Gold", "Unique"][i % 3];
              const m = DEFAULT_TIERS[tier];
              return (
                <tr key={g.id}>
                  <td className="bold">{g.name}</td>
                  <td>{tier === "Unique" ? <Badge tone="indigo">Unique</Badge> : tier === "Gold" ? <Badge tone="warning">Gold</Badge> : <Badge tone="neutral">Silver</Badge>}</td>
                  <td className="num mono">{g.agencies ? g.agencies.length : g.usedIn}</td>
                  {SEGMENTS.map((s) => <td key={s.key} className="num mono">{m[s.key]}%</td>)}
                  <td className="col-actions"><Button kind="secondary" size="sm" icon={<Icon.Edit />} onClick={() => setEdit(g)}>Adjust</Button></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      <AdjustMarkupModal entity={edit} kind="group" onClose={() => setEdit(null)} />
    </>
  );
}

function AdjustMarkupModal({ entity, kind, onClose }) {
  const overridesRef = React.useRef({});
  if (entity) {
    overridesRef.current = {};
  }
  if (!entity) return null;
  const tier = entity.markup === "Unique" ? "Unique" : entity.markup === "Gold" ? "Gold" : "Silver";
  const base = DEFAULT_TIERS[tier];
  return (
    <Modal open onClose={onClose} title={`Adjust markup · ${entity.name}`} size="lg"
      footer={<><Button kind="secondary" onClick={onClose}>Cancel</Button>
              <Button kind="primary" icon={<Icon.Check />} onClick={async () => { try { if (kind === "agency" && window.TrekkoAPI) await window.TrekkoAPI.saveAgencyMarkupOverride(entity.id, overridesRef.current); toast({ title: "Markup updated", body: entity.name, tone: "success" }); } catch (e) { toast({ title: "Save failed", body: e.message, tone: "danger" }); } finally { onClose(); } }}>Save markup</Button></>}>
      <div className="row" style={{ gap: 10, marginBottom: 14 }}>
        <Field label="Base tier"><select className="select" defaultValue={tier}><option>Silver</option><option>Gold</option><option>Unique</option></select></Field>
        <div style={{ flex: 1 }} />
        <div className="tiny muted" style={{ alignSelf: "flex-end" }}>Set a per-segment override on top of the {kind} tier</div>
      </div>
      <table className="tbl">
        <thead><tr><th>Segment</th><th className="num">Tier default</th><th className="num">Custom markup</th><th className="num">Sell on €100 NET</th></tr></thead>
        <tbody>
          {SEGMENTS.map((s) => (
            <tr key={s.key}>
              <td><Tag kind={s.tag}>{s.label}</Tag></td>
              <td className="num mono muted">{base[s.key]}%</td>
              <td className="num"><input className="input" type="number" defaultValue={base[s.key]} onChange={(e) => { const v = parseFloat(e.target.value); if (!isNaN(v)) overridesRef.current[s.key] = v; else delete overridesRef.current[s.key]; }} style={{ width: 90, height: 30, marginLeft: "auto" }} /></td>
              <td className="num mono">€{(100 / (1 - base[s.key] / 100)).toFixed(2)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </Modal>
  );
}

window.PageMarkups = PageMarkups;
