// Forms tracking — global screen and per-team tab.
const { useState: useStateF, useMemo: useMemoF } = React;

const FORM_TYPES = [
  { id: 'saf', label: 'SAF purchasing application', icon: 'Dollar' },
  { id: 'travel', label: 'Travel itinerary', icon: 'MapPin' },
  { id: 'driver', label: 'Driver authorization', icon: 'ShieldCheck' },
  { id: 'incident', label: 'Incident / injury report', icon: 'AlertTriangle' },
  { id: 'officer', label: 'Officer registration', icon: 'User' },
  { id: 'equipment', label: 'Equipment request', icon: 'FileText' },
  { id: 'damage', label: 'Facility damage report', icon: 'Building' },
  { id: 'postevent', label: 'Post-event report', icon: 'CheckCircle' },
];

const FORM_STATUS = {
  submitted: { label: 'Submitted', kind: 'gold' },
  review: { label: 'Under review', kind: 'warning' },
  approved: { label: 'Approved', kind: 'success' },
  returned: { label: 'Returned · changes requested', kind: 'danger' },
  draft: { label: 'Draft from team', kind: 'neutral' },
};

// Build form submission seed data deterministically from teams + types
function buildForms() {
  const out = [];
  const teams = window.AppData.TEAMS;
  const samples = [
    { type: 'travel', detail: 'vs Davenport · Grand Rapids', status: 'review', daysAgo: 1 },
    { type: 'driver', detail: 'Alex Nguyen · van certification', status: 'approved', daysAgo: 3 },
    { type: 'travel', detail: 'vs Northwood · Midland', status: 'submitted', daysAgo: 0 },
    { type: 'incident', detail: 'Sprained ankle · practice', status: 'review', daysAgo: 2 },
    { type: 'officer', detail: '2026–27 captain · Jordan Patel', status: 'approved', daysAgo: 8 },
    { type: 'equipment', detail: 'Replacement jerseys · 6 units', status: 'returned', daysAgo: 4 },
    { type: 'postevent', detail: 'vs Aquinas · final score 2–1', status: 'approved', daysAgo: 5 },
    { type: 'damage', detail: 'Net rip · IM Field 1', status: 'review', daysAgo: 6 },
    { type: 'travel', detail: 'Lakeshore criterium · Muskegon', status: 'approved', daysAgo: 11 },
    { type: 'driver', detail: 'Riley Garcia · van certification', status: 'submitted', daysAgo: 0 },
    { type: 'officer', detail: 'Treasurer · Casey Brown', status: 'draft', daysAgo: 7 },
    { type: 'equipment', detail: 'Practice balls · 12 units', status: 'approved', daysAgo: 9 },
    { type: 'postevent', detail: 'vs Hope · home opener', status: 'approved', daysAgo: 12 },
    { type: 'incident', detail: 'Concussion protocol · player #14', status: 'returned', daysAgo: 3 },
    { type: 'travel', detail: 'Spring tournament · Indianapolis', status: 'submitted', daysAgo: 1 },
    { type: 'damage', detail: 'Scoreboard wiring · Court 2', status: 'submitted', daysAgo: 2 },
    { type: 'officer', detail: 'Vice president · Morgan Smith', status: 'approved', daysAgo: 14 },
    { type: 'equipment', detail: 'Stick wrap order', status: 'submitted', daysAgo: 0 },
    { type: 'postevent', detail: 'vs BGSU · away · L 3–4', status: 'approved', daysAgo: 18 },
    { type: 'travel', detail: 'vs Saginaw Valley · home', status: 'review', daysAgo: 4 },
  ];
  const reviewers = ['Justin Reilly','Zac Holland','Val Marquez','Stoney Carter','Maya Brooks'];
  const submitters = {
    't1': 'Riley Garcia · captain',
    't2': 'Sage Wilson · president',
    't3': 'Logan Thompson · captain',
    't4': 'Quinn Davis · president',
    't5': 'Avery Martin · president',
    't6': 'Jordan Patel · captain',
    't7': 'Skyler Lopez · president',
    't8': 'Drew Anderson · captain',
    't9': 'Hayden Moore · captain',
    't10': 'Reese Taylor · president',
    't11': 'Emerson Jackson · president',
    't12': 'Cameron White · captain',
  };
  let id = 0;
  teams.forEach((team, ti) => {
    // Each team gets 2-4 form submissions, deterministic from index
    const count = 2 + (ti % 3);
    for (let i = 0; i < count; i++) {
      const s = samples[(ti * 3 + i * 5) % samples.length];
      const submittedDate = new Date('2026-05-15T00:00:00');
      submittedDate.setDate(submittedDate.getDate() - s.daysAgo);
      const submittedAt = submittedDate.toISOString().slice(0, 10);
      const reviewer = ['approved','returned'].includes(s.status) ? reviewers[(ti + i) % reviewers.length] : null;
      const reviewedAt = reviewer ? (() => {
        const d = new Date(submittedDate);
        d.setDate(d.getDate() + 1);
        return d.toISOString().slice(0, 10);
      })() : null;
      out.push({
        id: 'f' + (id++),
        teamId: team.id,
        team: team.name,
        type: s.type,
        detail: s.detail,
        status: s.status,
        submittedBy: submitters[team.id] || 'Team officer',
        submittedAt,
        reviewer,
        reviewedAt,
      });
    }
  });
  return out;
}

window.AppData.FORMS = window.AppData.FORMS || buildForms();
window.AppData.FORM_TYPES = FORM_TYPES;
window.AppData.FORM_STATUS = FORM_STATUS;

function FormsScreen({ user, teamId, onOpenTeam }) {
  const store = window.AppStore.useStore();
  const allEntries = store.getAllFormEntries(teamId);
  const [filterStatus, setFilterStatus] = useStateF('all');
  const [filterType, setFilterType] = useStateF('all');
  const [sortKey, setSortKey] = useStateF('submittedAt');
  const [dir, setDir] = useStateF('desc');
  const [expanded, setExpanded] = useStateF(null);
  const [showSAFForm, setShowSAFForm] = useStateF(false);

  const canReview = user.role === 'super_admin' || user.role === 'staff_admin' || user.role === 'cs_president';
  const scoped = allEntries;

  const filtered = useMemoF(() => {
    let list = scoped.slice();
    if (filterStatus !== 'all') list = list.filter(f => f.status === filterStatus);
    if (filterType !== 'all') list = list.filter(f => f.type === filterType);
    list.sort((a, b) => {
      let av = a[sortKey], bv = b[sortKey];
      if (sortKey === 'team') { av = a.team; bv = b.team; }
      if (av < bv) return dir === 'asc' ? -1 : 1;
      if (av > bv) return dir === 'asc' ? 1 : -1;
      return 0;
    });
    return list;
  }, [scoped, filterStatus, filterType, sortKey, dir]);

  function onSort(k) {
    if (sortKey === k) setDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortKey(k); setDir('desc'); }
  }

  function mark(formId, newStatus) {
    // SAF entries cross-update through the store
    const entry = scoped.find(f => f.id === formId);
    if (entry && entry.isSAF) {
      const next = newStatus === 'approved' ? 'posted' : newStatus === 'returned' ? 'returned' : 'val-confirmed';
      window.AppStore.advanceSAF(entry.safId, next, user.name);
      return;
    }
    window.AppStore.updateForm(formId, {
      status: newStatus,
      reviewer: user.name,
      reviewedAt: new Date().toISOString().slice(0, 10),
    });
  }

  const counts = useMemoF(() => {
    const c = { submitted: 0, review: 0, approved: 0, returned: 0, draft: 0 };
    scoped.forEach(f => { c[f.status]++; });
    return c;
  }, [scoped]);

  const FORM_TYPES = window.AppData.FORM_TYPES;
  const FORM_STATUS = window.AppData.FORM_STATUS;
  const typeMap = Object.fromEntries(FORM_TYPES.map(t => [t.id, t]));

  const median = useMemoF(() => {
    const turnarounds = scoped
      .filter(f => f.reviewedAt && f.submittedAt)
      .map(f => Math.max(0, Math.round((new Date(f.reviewedAt) - new Date(f.submittedAt)) / 86400000)));
    if (turnarounds.length === 0) return null;
    turnarounds.sort((a, b) => a - b);
    return turnarounds[Math.floor(turnarounds.length / 2)];
  }, [scoped]);

  const oldestOpen = useMemoF(() => {
    const open = scoped.filter(f => f.status === 'submitted' || f.status === 'review');
    if (open.length === 0) return null;
    open.sort((a, b) => a.submittedAt.localeCompare(b.submittedAt));
    return open[0];
  }, [scoped]);

  return (
    <div data-screen-label={teamId ? '05c Team forms' : '07 Forms'}>
      {!teamId && (
        <div className="page-head">
          <div>
            <h1 className="page-title">Forms</h1>
            <div className="page-subtitle">Every team submission, from travel itineraries to SAF purchasing applications</div>
          </div>
          {canReview && (
            <button className="btn btn-primary" onClick={() => setShowSAFForm(true)}>
              <window.I.Plus size={14} /> New SAF on behalf of team
            </button>
          )}
        </div>
      )}
      {teamId && canReview && (
        <div className="flex-between mb-12">
          <div className="dim" style={{ fontSize: 12 }}>
            Submissions sync live with the Budget ledger. SAFs filed here appear under the team's allocation immediately.
          </div>
          <button className="btn btn-secondary btn-sm" onClick={() => setShowSAFForm(true)}>
            <window.I.Plus size={13} /> New SAF for this team
          </button>
        </div>
      )}

      {showSAFForm && (
        <window.SAFForm
          defaultTeamId={teamId}
          onCancel={() => setShowSAFForm(false)}
          onAdd={(rec) => {
            window.AppStore.addSAF({ ...rec, enteredBy: user.name });
            setShowSAFForm(false);
          }}
        />
      )}

      {!teamId && (
        <div className="metric-grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
          <div className="card metric warning">
            <div className="metric-label">
              <span className="pill-icon"><window.I.Inbox size={14} /></span>
              Awaiting review
            </div>
            <div className="metric-value">{counts.submitted + counts.review}</div>
            <div className="metric-trend">{counts.submitted} new · {counts.review} in progress</div>
          </div>
          <div className="card metric danger">
            <div className="metric-label">
              <span className="pill-icon"><window.I.RefreshCw size={14} /></span>
              Returned to team
            </div>
            <div className="metric-value">{counts.returned}</div>
            <div className="metric-trend">awaiting revisions</div>
          </div>
          <div className="card metric success">
            <div className="metric-label">
              <span className="pill-icon"><window.I.CheckCircle size={14} /></span>
              Approved this month
            </div>
            <div className="metric-value">{counts.approved}</div>
            <div className="metric-trend">median turnaround {median !== null ? `${median}d` : '—'}</div>
          </div>
          <div className="card metric">
            <div className="metric-label">
              <span className="pill-icon"><window.I.Clock size={14} /></span>
              Oldest open
            </div>
            <div className="metric-value" style={{ fontSize: 18 }}>
              {oldestOpen
                ? `${Math.max(0, Math.round((new Date('2026-05-15') - new Date(oldestOpen.submittedAt)) / 86400000))}d`
                : '—'}
            </div>
            <div className="metric-trend">{oldestOpen ? `${oldestOpen.team} · ${typeMap[oldestOpen.type]?.label}` : 'nothing waiting'}</div>
          </div>
        </div>
      )}

      <div className="card">
        <div className="flex-between" style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)' }}>
          <div className="flex-gap-8">
            <strong style={{ fontSize: 13 }}>{teamId ? 'Submissions' : 'All form submissions'}</strong>
            <span className="dim" style={{ fontSize: 12 }}>· {filtered.length} of {scoped.length}</span>
          </div>
          <div className="flex-gap-8" style={{ gap: 6 }}>
            <select className="select" value={filterType} onChange={e => setFilterType(e.target.value)} style={{ width: 'auto', padding: '5px 10px', fontSize: 12 }}>
              <option value="all">All types</option>
              {FORM_TYPES.map(t => <option key={t.id} value={t.id}>{t.label}</option>)}
            </select>
            {['all','submitted','review','approved','returned','draft'].map(s => (
              <button
                key={s}
                className={`btn btn-xs ${filterStatus === s ? 'btn-secondary' : 'btn-ghost'}`}
                onClick={() => setFilterStatus(s)}
              >
                {s === 'all' ? 'All' : FORM_STATUS[s].label.split(' · ')[0]}
              </button>
            ))}
          </div>
        </div>
        <div className="table-wrap">
          <table className="data">
            <thead>
              <tr>
                <th style={{ width: 28 }}></th>
                <window.SortHeader id="type" sortKey={sortKey} dir={dir} onSort={onSort}>Form</window.SortHeader>
                {!teamId && <window.SortHeader id="team" sortKey={sortKey} dir={dir} onSort={onSort}>Team</window.SortHeader>}
                <th>Submitted by</th>
                <window.SortHeader id="submittedAt" sortKey={sortKey} dir={dir} onSort={onSort}>Submitted</window.SortHeader>
                <window.SortHeader id="status" sortKey={sortKey} dir={dir} onSort={onSort}>Status</window.SortHeader>
                <th>Reviewer</th>
                <th style={{ textAlign: 'right' }}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.length === 0 ? (
                <tr><td colSpan={teamId ? 7 : 8}>
                  <div className="empty">
                    <div className="empty-icon"><window.I.FileText size={20} /></div>
                    <div className="empty-title">No forms match this filter</div>
                    <div className="empty-msg">Try a different status or form type.</div>
                    <button className="btn btn-secondary btn-sm" onClick={() => { setFilterStatus('all'); setFilterType('all'); }}>Clear filters</button>
                  </div>
                </td></tr>
              ) : filtered.map(f => {
                const t = typeMap[f.type];
                const Ic = window.I[t.icon];
                const st = FORM_STATUS[f.status];
                const isOpen = expanded === f.id;
                const open = f.status === 'submitted' || f.status === 'review';
                return (
                  <React.Fragment key={f.id}>
                    <tr className="clickable" onClick={() => setExpanded(isOpen ? null : f.id)}>
                      <td style={{ color: 'var(--text-3)' }}>
                        <window.I.ChevronRight size={14} style={{ transform: isOpen ? 'rotate(90deg)' : 'none', transition: 'transform 0.15s' }} />
                      </td>
                      <td>
                        <div className="flex-gap-8">
                          <span style={{ color: 'var(--text-2)' }}><Ic size={14} /></span>
                          <div>
                            <div style={{ fontWeight: 600 }}>{t.label}</div>
                            <div className="cell-muted" style={{ fontSize: 11 }}>{f.detail}</div>
                          </div>
                        </div>
                      </td>
                      {!teamId && (
                        <td>
                          <button
                            className="btn btn-ghost btn-xs"
                            onClick={(e) => { e.stopPropagation(); onOpenTeam && onOpenTeam(f.teamId); }}
                          >
                            {f.team}
                          </button>
                        </td>
                      )}
                      <td className="cell-muted">{f.submittedBy}</td>
                      <td className="cell-mono cell-muted">{f.submittedAt}</td>
                      <td><span className={`badge ${st.kind} dot`}>{st.label}</span></td>
                      <td className="cell-muted">
                        {f.reviewer
                          ? <span>{f.reviewer}<span className="dim" style={{ fontSize: 11 }}> · {f.reviewedAt}</span></span>
                          : <span className="dim">—</span>}
                      </td>
                      <td style={{ textAlign: 'right' }}>
                        {canReview && open ? (
                          <div className="flex-gap-8" style={{ justifyContent: 'flex-end', gap: 4 }}>
                            <button
                              className="btn btn-success btn-xs"
                              onClick={(e) => { e.stopPropagation(); mark(f.id, 'approved'); }}
                            >
                              <window.I.Check size={11} /> Approve
                            </button>
                            <button
                              className="btn btn-deny btn-xs"
                              onClick={(e) => { e.stopPropagation(); mark(f.id, 'returned'); }}
                            >
                              <window.I.RefreshCw size={11} /> Return
                            </button>
                          </div>
                        ) : (
                          <span className="dim" style={{ fontSize: 11 }}>—</span>
                        )}
                      </td>
                    </tr>
                    {isOpen && (
                      <tr>
                        <td colSpan={teamId ? 7 : 8} style={{ background: 'var(--bg)', padding: 0 }}>
                          {f.isSAF
                            ? <window.SAFDetail rec={f.saf} user={user} onAdvance={(safId, next) => window.AppStore.advanceSAF(safId, next, user.name)} />
                            : <FormDetail form={f} typeMeta={t} />}
                        </td>
                      </tr>
                    )}
                  </React.Fragment>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function FormDetail({ form, typeMeta }) {
  const FORM_STATUS = window.AppData.FORM_STATUS;
  const st = FORM_STATUS[form.status];
  const timeline = [
    { at: form.submittedAt, by: form.submittedBy, label: 'Submitted via Canvas' },
    form.status !== 'submitted' && form.status !== 'draft' && { at: form.submittedAt, by: form.reviewer || 'Staff', label: 'Picked up for review' },
    form.reviewer && form.reviewedAt && {
      at: form.reviewedAt,
      by: form.reviewer,
      label: form.status === 'approved' ? 'Approved' : form.status === 'returned' ? 'Returned with changes' : 'Updated',
    },
  ].filter(Boolean);

  return (
    <div style={{ padding: '20px 24px', display: 'grid', gridTemplateColumns: '1fr 280px', gap: 32 }}>
      <div>
        <div className="section-title" style={{ margin: '0 0 10px' }}>Submission detail</div>
        <div className="card" style={{ padding: 16, background: 'var(--surface)' }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>{typeMeta.label}</div>
          <div className="dim" style={{ fontSize: 12, marginBottom: 14 }}>{form.detail}</div>
          <dl className="approval-meta">
            <dt>Team</dt><dd>{form.team}</dd>
            <dt>Submitted by</dt><dd>{form.submittedBy}</dd>
            <dt>Submitted on</dt><dd>{form.submittedAt}</dd>
            <dt>Current status</dt><dd><span className={`badge ${st.kind} dot`}>{st.label}</span></dd>
            {form.reviewer && (<><dt>Reviewer</dt><dd>{form.reviewer} · {form.reviewedAt}</dd></>)}
          </dl>
        </div>
      </div>
      <div>
        <div className="section-title" style={{ margin: '0 0 10px' }}>Timeline</div>
        <div className="card" style={{ padding: 16, background: 'var(--surface)' }}>
          <ol style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
            {timeline.map((step, i) => (
              <li key={i} style={{ display: 'flex', gap: 10, fontSize: 12 }}>
                <span style={{
                  width: 8, height: 8, borderRadius: 50,
                  background: i === timeline.length - 1 ? 'var(--gold)' : 'var(--border-2)',
                  marginTop: 5, flexShrink: 0,
                }} />
                <div>
                  <div style={{ fontWeight: 600 }}>{step.label}</div>
                  <div className="dim">{step.by} · {step.at}</div>
                </div>
              </li>
            ))}
          </ol>
        </div>
      </div>
    </div>
  );
}

window.FormsScreen = FormsScreen;
