// admin-teacher-finder.jsx
//
// Admin tab: search Google Maps for tutors near a student address, see drive
// times, and message them through Sales Message with a customizable template.
//
// Talks to three Vercel serverless functions:
//   POST /api/teacher-search        — geocode + Places + Distance Matrix
//   POST /api/teacher-outreach      — create Sales Message contact + send SMS
//   GET/PUT /api/outreach-template  — read/write the saved message template
//
// All API calls go out with Authorization: Bearer <Supabase JWT>; the server
// re-checks the user is in admin_users before doing anything sensitive.

const TF_TONE = {
  page:        'oklch(97% 0.006 60)',
  card:        '#fff',
  border:      'oklch(90% 0.01 265)',
  text:        'oklch(18% 0.03 265)',
  muted:       'oklch(55% 0.03 265)',
  mutedLight:  'oklch(70% 0.03 265)',
  accent:      'oklch(72% 0.17 80)',  // honey / gold
  accentText:  'oklch(22% 0.06 265)',
  success:     'oklch(60% 0.14 145)',
  successBg:   'oklch(95% 0.06 145)',
  danger:      'oklch(58% 0.18 25)',
  dangerBg:    'oklch(95% 0.05 25)',
  pillLocal:   'oklch(75% 0.14 150)',
  pillReason:  'oklch(78% 0.14 90)',
  pillFar:     'oklch(75% 0.10 50)',
};

async function tfAuthFetch(url, opts = {}) {
  // Pull the current Supabase session JWT and attach it. If no session, return null.
  const { data } = await window.supa.auth.getSession();
  const token = data?.session?.access_token;
  if (!token) throw new Error('Not signed in');
  return fetch(url, {
    ...opts,
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
      ...(opts.headers || {}),
    },
  });
}

const AdminTeacherFinder = () => {
  const [studentAddr, setStudentAddr] = React.useState('');
  const [topic, setTopic] = React.useState('');
  const [maxMin, setMaxMin] = React.useState(50);
  const [searching, setSearching] = React.useState(false);
  const [result, setResult] = React.useState(null);  // { origin, usable, dropped, maxMin }
  const [err, setErr] = React.useState('');
  const [template, setTemplate] = React.useState('');
  const [outboundEnabled, setOutboundEnabled] = React.useState(false);
  const [showDropped, setShowDropped] = React.useState(false);

  // Load saved template + outbound state on mount
  React.useEffect(() => {
    (async () => {
      try {
        const r = await tfAuthFetch('/api/outreach-template');
        const body = await r.json();
        if (r.ok) {
          setTemplate(body.template || '');
          setOutboundEnabled(!!body.outboundEnabled);
        }
      } catch (e) {
        console.warn('Settings load failed:', e.message);
      }
    })();
  }, []);

  const runSearch = async () => {
    if (!studentAddr.trim() || !topic.trim()) {
      setErr('Both address and topic are required.');
      return;
    }
    setSearching(true);
    setErr('');
    setResult(null);
    try {
      const r = await tfAuthFetch('/api/teacher-search', {
        method: 'POST',
        body: JSON.stringify({ studentAddr, topic, maxMin: Number(maxMin) }),
      });
      const body = await r.json();
      if (!r.ok || !body.ok) throw new Error(body.error || `HTTP ${r.status}`);
      setResult(body);
    } catch (e) {
      setErr(e.message || 'Search failed');
    } finally {
      setSearching(false);
    }
  };

  return (
    <div style={{ fontFamily: "'Plus Jakarta Sans', sans-serif", color: TF_TONE.text }}>

      {/* Header */}
      <div style={{ marginBottom: 18 }}>
        <h2 style={{ margin: 0, fontFamily: "'Cormorant Garamond', serif", fontSize: 28, fontWeight: 700, color: TF_TONE.text }}>
          Teacher Finder
        </h2>
        <div style={{ fontSize: 13, color: TF_TONE.muted, marginTop: 4 }}>
          Search Google Maps for tutors near a student, see drive times, and message them through Sales Message.
        </div>
      </div>

      {/* Kill-switch */}
      <window.TFKillSwitch outboundEnabled={outboundEnabled} onToggled={setOutboundEnabled} />

      {/* Template editor */}
      <window.TFTemplateEditor initialTemplate={template} onSaved={setTemplate} />

      {/* Search form */}
      <div style={{
        background: TF_TONE.card, border: `1px solid ${TF_TONE.border}`, borderRadius: 14,
        padding: '18px 20px', marginBottom: 20,
      }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 2fr 130px auto', gap: 12, alignItems: 'end' }}>
          <div>
            <label style={{ display: 'block', fontSize: 11, fontWeight: 700, color: TF_TONE.muted, marginBottom: 5, textTransform: 'uppercase', letterSpacing: '0.05em' }}>Student address or ZIP</label>
            <input
              value={studentAddr}
              onChange={e => setStudentAddr(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && runSearch()}
              placeholder="e.g. Bay Shore NY 11706"
              style={{ width: '100%', boxSizing: 'border-box', border: `1px solid ${TF_TONE.border}`, borderRadius: 8, padding: '9px 11px', fontSize: 13, fontFamily: 'inherit', color: TF_TONE.text, background: '#fff' }}
            />
          </div>
          <div>
            <label style={{ display: 'block', fontSize: 11, fontWeight: 700, color: TF_TONE.muted, marginBottom: 5, textTransform: 'uppercase', letterSpacing: '0.05em' }}>Topic</label>
            <input
              value={topic}
              onChange={e => setTopic(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && runSearch()}
              placeholder="e.g. piano lessons, krav maga"
              style={{ width: '100%', boxSizing: 'border-box', border: `1px solid ${TF_TONE.border}`, borderRadius: 8, padding: '9px 11px', fontSize: 13, fontFamily: 'inherit', color: TF_TONE.text, background: '#fff' }}
            />
          </div>
          <div>
            <label style={{ display: 'block', fontSize: 11, fontWeight: 700, color: TF_TONE.muted, marginBottom: 5, textTransform: 'uppercase', letterSpacing: '0.05em' }}>Max drive (min)</label>
            <input
              type="number"
              min={5}
              max={120}
              step={5}
              value={maxMin}
              onChange={e => setMaxMin(e.target.value)}
              style={{ width: '100%', boxSizing: 'border-box', border: `1px solid ${TF_TONE.border}`, borderRadius: 8, padding: '9px 11px', fontSize: 13, fontFamily: 'inherit', color: TF_TONE.text, background: '#fff' }}
            />
          </div>
          <button
            onClick={runSearch}
            disabled={searching}
            style={{
              background: TF_TONE.accent, color: TF_TONE.accentText, border: 'none', borderRadius: 8,
              padding: '10px 22px', fontSize: 13, fontWeight: 700, cursor: searching ? 'wait' : 'pointer',
              fontFamily: "'Plus Jakarta Sans', sans-serif", letterSpacing: '0.02em',
              opacity: searching ? 0.7 : 1, height: 38, whiteSpace: 'nowrap',
            }}
          >{searching ? 'Searching…' : 'Search'}</button>
        </div>
        {err && (
          <div style={{ marginTop: 12, background: TF_TONE.dangerBg, color: TF_TONE.danger, padding: '10px 12px', borderRadius: 8, fontSize: 12 }}>
            {err}
          </div>
        )}
      </div>

      {/* Results */}
      {result && (
        <div>
          <div style={{ fontSize: 12, color: TF_TONE.muted, marginBottom: 8 }}>
            <span style={{ marginRight: 4 }}>📍 Student located at:</span>
            <strong style={{ color: TF_TONE.text }}>{result.origin.formatted}</strong>
          </div>

          {result.usable.length === 0 ? (
            <div style={{ background: TF_TONE.dangerBg, color: TF_TONE.danger, padding: '14px 16px', borderRadius: 10, fontSize: 13, fontWeight: 600 }}>
              ❌ Area unavailable — no teachers within {result.maxMin} minutes.
            </div>
          ) : (
            <>
              <div style={{ background: TF_TONE.successBg, color: TF_TONE.success, padding: '10px 14px', borderRadius: 10, fontSize: 13, fontWeight: 600, marginBottom: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 10 }}>
                <span>Found {result.usable.length} reachable teacher{result.usable.length === 1 ? '' : 's'} within {result.maxMin} min.</span>
                <span style={{ fontSize: 10, fontWeight: 500, opacity: 0.85, whiteSpace: 'nowrap' }}>
                  {result.totalUnique || (result.usable.length + result.dropped.length)} unique results across {(result.variantsSearched || []).length} query variants
                </span>
              </div>

              <div style={{ background: TF_TONE.card, border: `1px solid ${TF_TONE.border}`, borderRadius: 12, overflow: 'hidden' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                  <thead>
                    <tr style={{ background: TF_TONE.page }}>
                      <th style={{ textAlign: 'left', padding: '10px 14px', fontSize: 10, fontWeight: 700, color: TF_TONE.muted, textTransform: 'uppercase', letterSpacing: '0.05em' }}>Teacher</th>
                      <th style={{ textAlign: 'left', padding: '10px 8px', fontSize: 10, fontWeight: 700, color: TF_TONE.muted, textTransform: 'uppercase', letterSpacing: '0.05em' }}>Drive</th>
                      <th style={{ textAlign: 'left', padding: '10px 8px', fontSize: 10, fontWeight: 700, color: TF_TONE.muted, textTransform: 'uppercase', letterSpacing: '0.05em' }}>Phone</th>
                      <th style={{ textAlign: 'left', padding: '10px 8px', fontSize: 10, fontWeight: 700, color: TF_TONE.muted, textTransform: 'uppercase', letterSpacing: '0.05em' }}>Rating</th>
                      <th style={{ textAlign: 'left', padding: '10px 8px', fontSize: 10, fontWeight: 700, color: TF_TONE.muted, textTransform: 'uppercase', letterSpacing: '0.05em' }}>Website</th>
                      <th style={{ textAlign: 'right', padding: '10px 14px', fontSize: 10, fontWeight: 700, color: TF_TONE.muted, textTransform: 'uppercase', letterSpacing: '0.05em' }}>Outreach</th>
                    </tr>
                  </thead>
                  <tbody>
                    {result.usable.map((row, i) => <window.TFRow key={i} row={row} topic={topic} area={studentAddr} searchId={result.searchId} outboundEnabled={outboundEnabled} />)}
                  </tbody>
                </table>
              </div>

              {result.dropped.length > 0 && (
                <div style={{ marginTop: 14 }}>
                  <button
                    onClick={() => setShowDropped(s => !s)}
                    style={{
                      background: 'transparent', border: `1px solid ${TF_TONE.border}`, borderRadius: 8,
                      padding: '7px 13px', fontSize: 12, fontWeight: 600, color: TF_TONE.muted,
                      cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif",
                    }}
                  >{showDropped ? 'Hide' : 'Show'} {result.dropped.length} teacher{result.dropped.length === 1 ? '' : 's'} dropped (over {result.maxMin} min)</button>
                  {showDropped && (
                    <div style={{ marginTop: 10, background: TF_TONE.card, border: `1px solid ${TF_TONE.border}`, borderRadius: 12, overflow: 'hidden' }}>
                      <table style={{ width: '100%', borderCollapse: 'collapse', opacity: 0.7 }}>
                        <tbody>
                          {result.dropped.map((row, i) => <window.TFRow key={i} row={row} topic={topic} area={studentAddr} searchId={result.searchId} outboundEnabled={outboundEnabled} />)}
                        </tbody>
                      </table>
                    </div>
                  )}
                </div>
              )}
            </>
          )}
        </div>
      )}
    </div>
  );
};

window.AdminTeacherFinder = AdminTeacherFinder;
