/* global React */
const { useState, useMemo } = React;

const TICKETS = [
  { id: 2841, title: "Rslot PSU2 sur srv-lyon-db-01", type: "maintenance", status: "in-progress", priority: "high", room: "Hall B", rack: "mars-04", eq: "srv-lyon-db-01", created: "3h", updated: "12 min", creator: "M. Cooper", assignee: "Smart hands · DC tiers", due: "Today 18:00", steps: 4, stepsDone: 2 },
  { id: 2840, title: "Installation 2× Dell R760 en mars-04 U10-U11", type: "install", status: "open", priority: "normal", room: "Hall B", rack: "mars-04", eq: "—", created: "1j", updated: "6h", creator: "L. Wright", assignee: "Smart hands · DC tiers", due: "Vendredi", steps: 6, stepsDone: 0 },
  { id: 2839, title: "Decom 4 servers HPE en mercury-13", type: "decom", status: "in-progress", priority: "normal", room: "Hall A", rack: "mercury-13", eq: "srv-lyon-app-01..04", created: "2j", updated: "1j", creator: "M. Cooper", assignee: "Équipe interne", due: "Dans 5 jours", steps: 8, stepsDone: 5 },
  { id: 2838, title: "Cabling fibre LC vers ToR mars-07", type: "install", status: "done", priority: "low", room: "Hall B", rack: "mars-07", eq: "sw-lyon-b04-tor-01", created: "4j", updated: "2j", creator: "T. Roux", assignee: "Smart hands · DC tiers", due: "—", steps: 3, stepsDone: 3 },
  { id: 2837, title: "Verify unbalanced load PDU A/B en titan-31", type: "maintenance", status: "open", priority: "high", room: "Hall D", rack: "titan-31", eq: "—", created: "5j", updated: "2j", creator: "M. Cooper", assignee: "—", due: "Readndi", steps: 5, stepsDone: 0 },
  { id: 2836, title: "Rslot disque 4 sur san-lyon-b02-01", type: "maintenance", status: "done", priority: "high", room: "Hall B", rack: "mars-04", eq: "san-lyon-b02-01", created: "7j", updated: "6j", creator: "L. Wright", assignee: "Smart hands · DC tiers", due: "—", steps: 4, stepsDone: 4 },
  { id: 2835, title: "Rebranding asset tag sur 12 servers en mercury-15", type: "maintenance", status: "cancelled", priority: "low", room: "Hall A", rack: "mercury-15", eq: "—", created: "9j", updated: "8j", creator: "T. Roux", assignee: "Équipe interne", due: "—", steps: 2, stepsDone: 0 },
];

const SELECTED_TICKET = TICKETS[0];
const STEPS = [
  { id: 1, title: "Prebye la byt detached", desc: "PSU Dell 1100W ref D1100E-S0 · stock rack byts · armoire S2", done: true, by: "Smart hands", at: "13:42", photos: 1, comment: "Byt sortie du stock, control visuel OK." },
  { id: 2, title: "Identifier physiquement srv-lyon-db-01 (mars-04 U15)", desc: "Label asset LYN-B02-15. Verify LED localisation enablede à distance.", done: true, by: "Smart hands", at: "14:08", photos: 2, comment: "Identified, LED bleue confirmed, label photo en byt jointe." },
  { id: 3, title: "Unplug PSU2 (PDU B prise 7) puis échanger", desc: "Verify bandeau redondant : PSU1 doit rester active side PDU A. Photo avant/after obligatoire.", done: false, by: null, at: null, photos: 0, comment: "" },
  { id: 4, title: "Test, photos, back cabling", desc: "Voyants verts sur les 2 PSU. Photo face rear cabled propre.", done: false, by: null, at: null, photos: 0, comment: "" },
];

const STATUS_LABEL = { open: "Open", "in-progress": "In progress", done: "Fait", cancelled: "Cancelled" };
const TYPE_LABEL = { install: "Installation", maintenance: "Maintenance", decom: "Decom" };

function Pill({ status }) {
  return <span className={`pill st-${status}`}>{STATUS_LABEL[status]}</span>;
}
function TypePill({ type }) {
  return <span className={`pill ty-${type}`}>{TYPE_LABEL[type]}</span>;
}
function PriPill({ p }) {
  return <span className={`pill pr-${p}`}>{p === "high" ? "● High" : p === "normal" ? "● Normale" : "● Lowse"}</span>;
}

function TicketsList({ filter, setFilter, search, setSearch, selected, onSelect }) {
  const items = useMemo(() => {
    let xs = TICKETS;
    if (filter === "mine") xs = xs.filter(t => t.creator === "M. Cooper");
    else if (filter === "open") xs = xs.filter(t => t.status === "open" || t.status === "in-progress");
    else if (filter === "closed") xs = xs.filter(t => t.status === "done" || t.status === "cancelled");
    if (search) {
      const s = search.toLowerCase();
      xs = xs.filter(t => t.title.toLowerCase().includes(s) || String(t.id).includes(s) || t.rack.toLowerCase().includes(s));
    }
    return xs;
  }, [filter, search]);

  const tabs = [
    { id: "all", label: "All", count: TICKETS.length },
    { id: "mine", label: "My tickets", count: TICKETS.filter(t => t.creator === "M. Cooper").length },
    { id: "open", label: "Opens", count: TICKETS.filter(t => t.status === "open" || t.status === "in-progress").length },
    { id: "closed", label: "Closeds", count: TICKETS.filter(t => t.status === "done" || t.status === "cancelled").length },
  ];

  return (
    <div className="tickets-list">
      <div className="tk-list-head">
        <div className="tk-tabs">
          {tabs.map(t => (
            <button key={t.id} className={`tk-tab ${filter === t.id ? "active" : ""}`} onClick={() => setFilter(t.id)}>
              {t.label}<span className="tk-tab-count">{t.count}</span>
            </button>
          ))}
        </div>
        <div className="tk-search">
          <input placeholder="Search number, titre, rack…" value={search} onChange={e => setSearch(e.target.value)}/>
        </div>
      </div>

      <div className="tk-table-wrap">
        <table className="tk-table">
          <thead>
            <tr>
              <th style={{ width: 70 }}>#</th>
              <th>Titre</th>
              <th style={{ width: 110 }}>Type</th>
              <th style={{ width: 110 }}>Target</th>
              <th style={{ width: 110 }}>Status</th>
              <th style={{ width: 100 }}>Priority</th>
              <th style={{ width: 140 }}>Assigned</th>
              <th style={{ width: 100 }}>Steps</th>
              <th style={{ width: 110 }}>Due</th>
              <th style={{ width: 110 }}>Updated</th>
            </tr>
          </thead>
          <tbody>
            {items.map(t => (
              <tr key={t.id} className={selected === t.id ? "selected" : ""} onClick={() => onSelect(t.id)}>
                <td className="mono dim">#{t.id}</td>
                <td className="title-cell">
                  <div className="t-title">{t.title}</div>
                  <div className="t-sub">by {t.creator} · {t.created}</div>
                </td>
                <td><TypePill type={t.type}/></td>
                <td className="mono"><b>{t.rack}</b><div className="dim sm">{t.room}</div></td>
                <td><Pill status={t.status}/></td>
                <td><PriPill p={t.priority}/></td>
                <td className="sm">{t.assignee}</td>
                <td>
                  <div className="step-prog">
                    <div className="step-prog-bar"><div style={{ width: `${t.stepsDone / t.steps * 100}%` }}/></div>
                    <span className="mono dim sm">{t.stepsDone}/{t.steps}</span>
                  </div>
                </td>
                <td className="sm">{t.due}</td>
                <td className="sm dim">{t.updated}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function TicketDetail({ ticket, onClose }) {
  const [stepsState, setStepsState] = useState(STEPS);
  const toggle = (id) => setStepsState(xs => xs.map(s => s.id === id ? { ...s, done: !s.done } : s));

  return (
    <div className="ticket-detail">
      <div className="td-head">
        <div className="td-head-left">
          <button className="icon-btn" onClick={onClose}>←</button>
          <div>
            <div className="td-num mono">#{ticket.id}</div>
            <h2 className="td-title">{ticket.title}</h2>
            <div className="td-meta">
              <TypePill type={ticket.type}/>
              <Pill status={ticket.status}/>
              <PriPill p={ticket.priority}/>
              <span className="dim sm">Open {ticket.created} by <b>{ticket.creator}</b></span>
            </div>
          </div>
        </div>
        <div className="td-head-actions">
          <button className="btn">Assigner</button>
          <div className="status-flow">
            <button className="sf-step done">Open</button>
            <span className="sf-arrow">→</span>
            <button className="sf-step active">In progress</button>
            <span className="sf-arrow">→</span>
            <button className="sf-step">Fait</button>
          </div>
          <button className="btn primary">Update</button>
        </div>
      </div>

      <div className="td-body">
        <div className="td-main">
          <section className="td-section">
            <h3>Description</h3>
            <p className="td-desc">
              Le PSU2 de <b className="mono">srv-lyon-db-01</b> remonte un état degraded depuis 6h (alert SNMP fan-fail). Cable PSU2 → PDU B prise 7. Le server tourne currentlement sur PSU1 uniquement, l'intervention doit être faite <b>avant 18h</b> pour ne pas exposer la base de data. Byt detached already sortie du stock.
            </p>
          </section>

          <section className="td-section">
            <div className="td-section-head">
              <h3>Steps</h3>
              <span className="dim sm">{stepsState.filter(s => s.done).length}/{stepsState.length} completeed</span>
            </div>
            <ol className="steps">
              {stepsState.map((s, i) => (
                <li key={s.id} className={`step ${s.done ? "done" : ""}`}>
                  <div className="step-num">
                    <button className="step-check" onClick={() => toggle(s.id)} aria-label="Cocher">
                      {s.done ? "✓" : i + 1}
                    </button>
                  </div>
                  <div className="step-body">
                    <div className="step-title">{s.title}</div>
                    <div className="step-desc">{s.desc}</div>
                    {s.done && (
                      <div className="step-meta">
                        <span className="dim sm mono">Validated by {s.by} · {s.at}</span>
                        {s.photos > 0 && <span className="step-photos">📷 {s.photos} photo{s.photos > 1 ? "s" : ""}</span>}
                      </div>
                    )}
                    {s.done && s.comment && <div className="step-comment">{s.comment}</div>}
                    {!s.done && (
                      <div className="step-input">
                        <textarea placeholder="Comment de l'operator…" rows="2"/>
                        <div className="step-input-foot">
                          <button className="upload-zone">＋ Drag une photo</button>
                          <button className="btn sm primary">Validate l'step</button>
                        </div>
                      </div>
                    )}
                  </div>
                </li>
              ))}
            </ol>
          </section>

          <section className="td-section">
            <h3>Activity</h3>
            <ul className="activity-feed">
              <li><span className="af-time mono">14:08</span><span><b>Smart hands</b> a checked l'step 2 et added 2 photos</span></li>
              <li><span className="af-time mono">13:42</span><span><b>Smart hands</b> a checked l'step 1</span></li>
              <li><span className="af-time mono">13:30</span><span><b>M. Cooper</b> a past le ticket en <i>In progress</i></span></li>
              <li><span className="af-time mono">11:14</span><span><b>M. Cooper</b> a assigned à <i>Smart hands · DC tiers</i></span></li>
              <li><span className="af-time mono">11:12</span><span><b>M. Cooper</b> a created le ticket à bytir d'une alert SNMP</span></li>
            </ul>
          </section>

          <section className="td-section">
            <h3>Comment</h3>
            <div className="comment-box">
              <textarea placeholder="Ajouter un commentaire (markdown supported)…" rows="3"/>
              <div className="comment-foot">
                <button className="upload-zone">＋ Attachments</button>
                <button className="btn primary">Publier</button>
              </div>
            </div>
          </section>
        </div>

        <aside className="td-side">
          <div className="td-card">
            <div className="td-card-title">Details</div>
            <div className="kv">
              <div><span>Type</span><b><TypePill type={ticket.type}/></b></div>
              <div><span>Priority</span><b><PriPill p={ticket.priority}/></b></div>
              <div><span>Due</span><b className="warn">{ticket.due}</b></div>
              <div><span>Assigned to</span><b>{ticket.assignee}</b></div>
              <div><span>Created by</span><b>{ticket.creator}</b></div>
              <div><span>Created</span><b>05/05/2026 11:12</b></div>
              <div><span>Updated</span><b>{ticket.updated}</b></div>
            </div>
          </div>

          <div className="td-card">
            <div className="td-card-title">Targets</div>
            <ul className="targets">
              <li>
                <span className="tg-icon">▣</span>
                <div>
                  <div className="tg-name mono">mars-04 / U15</div>
                  <div className="tg-sub">Hall B · srv-lyon-db-01</div>
                </div>
                <a href="bay.html" className="tg-link">View →</a>
              </li>
              <li>
                <span className="tg-icon">⚡</span>
                <div>
                  <div className="tg-name mono">PDU-B · prise 7</div>
                  <div className="tg-sub">mars-04 · Eaton ePDU G3</div>
                </div>
                <a href="#" className="tg-link">View →</a>
              </li>
            </ul>
          </div>

          <div className="td-card">
            <div className="td-card-title">Attachments</div>
            <ul className="attachments">
              <li><span className="att-ic">📄</span><div><div>datasheet-PSU-D1100E.pdf</div><div className="dim sm">412 Ko · joint à la creation</div></div></li>
              <li><span className="att-ic">🖼️</span><div><div>etiquette-asset-LYN-B02-15.jpg</div><div className="dim sm">2.1 Mo · step 2</div></div></li>
              <li><span className="att-ic">🖼️</span><div><div>face-arriere-avant.jpg</div><div className="dim sm">1.8 Mo · step 2</div></div></li>
            </ul>
          </div>

          <div className="td-card warn-card">
            <div className="td-card-title">⚠ Risque</div>
            <p>Le server tourne sur PSU1 uniquement depuis l'alert. Alle manipulation side PDU A doit être deferred tant que ce ticket n'est pas clos.</p>
          </div>
        </aside>
      </div>
    </div>
  );
}

function TicketsApp() {
  const [filter, setFilter] = useState("all");
  const [search, setSearch] = useState("");
  const [selected, setSelected] = useState(null);

  const ticket = useMemo(() => TICKETS.find(t => t.id === selected), [selected]);

  return (
    <div className="tickets-page" data-screen-label="Tickets — List & detail">
      <div className="tk-page-head">
        <div>
          <div className="dim sm">Site mars-7 / Tickets</div>
          <h1>Tickets <span className="dim sm">· 7 actives sur le byc</span></h1>
        </div>
        <div className="tk-page-actions">
          <button className="btn">Filters advanced</button>
          <button className="btn">Export CSV</button>
          <button className="btn primary">+ New ticket</button>
        </div>
      </div>

      {ticket ? (
        <TicketDetail ticket={ticket} onClose={() => setSelected(null)}/>
      ) : (
        <TicketsList filter={filter} setFilter={setFilter} search={search} setSearch={setSearch} selected={selected} onSelect={setSelected}/>
      )}
    </div>
  );
}

window.TicketsApp = TicketsApp;
