// src/features/bookings/ui/session-feedback.jsx
//
// Per-session rating + optional note, both sides:
//   - StudentSessionFeedbackBanner — drop into student-home; lists past
//     completed lessons the student hasn't rated and opens the modal per row.
//   - StudentSessionFeedbackModal  — the 1-5 + note modal.
//   - TeacherSessionRatingControl  — small 5-star input slotted into
//     LessonDetailPopup above the existing notes textarea.
//
// Writes go through window.Bookings.db.studentSubmitSessionFeedback /
// .saveSessionRating (see src/features/bookings/data.js). Schema lives in
// supabase/v72-schema.sql — five additive columns on bookings + two
// SECURITY DEFINER RPCs.

// ── Shared 5-star input ──────────────────────────────────────────────
// Used by both the student modal and the teacher control. Controlled
// component — parent owns the value. Stars match the visual treatment
// of the existing public-review modal (review-form.jsx) so the two
// rating surfaces feel like the same product.
const SessionFeedbackStars = ({ value, onChange, size = 32 }) => (
  <div style={{ display: 'flex', gap: 6 }}>
    {[1, 2, 3, 4, 5].map(n => (
      <button key={n} type="button" onClick={() => onChange(n)}
        aria-label={`${n} star${n > 1 ? 's' : ''}`}
        style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, lineHeight: 0 }}>
        <svg width={size} height={size} viewBox="0 0 16 16">
          <path d="M8 1.5l1.8 3.7 4.1.6-3 2.9.7 4.1L8 10.8l-3.6 1.9.7-4.1-3-2.9 4.1-.6z"
            fill={n <= value ? 'oklch(72% 0.17 80)' : 'oklch(88% 0.015 60)'} />
        </svg>
      </button>
    ))}
  </div>
);

// ── Student modal ────────────────────────────────────────────────────
const StudentSessionFeedbackModal = ({ booking, onClose, onSubmitted }) => {
  const [rating, setRating] = React.useState(5);
  const [note, setNote]     = React.useState('');
  const [busy, setBusy]     = React.useState(false);
  const [error, setError]   = React.useState(null);

  const submit = async () => {
    setError(null);
    setBusy(true);
    try {
      await window.Bookings.db.studentSubmitSessionFeedback(booking.id, rating, note);
      if (onSubmitted) onSubmitted();
      onClose();
    } catch (e) {
      setError(e.message || 'Could not submit. Please try again.');
    } finally {
      setBusy(false);
    }
  };

  const when = new Date(booking.scheduledAt || booking.scheduled_at);
  const dateStr = when.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' });

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(15,20,40,0.55)', backdropFilter: 'blur(6px)',
      zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 460, background: '#fff', borderRadius: 18, padding: 28,
        boxShadow: '0 20px 60px rgba(0,0,0,0.25)', fontFamily: "'Plus Jakarta Sans', sans-serif",
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.14em', color: 'oklch(72% 0.17 80)', textTransform: 'uppercase', marginBottom: 6 }}>
              How was your session?
            </div>
            <h2 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 22, fontWeight: 600, color: 'oklch(22% 0.06 265)', lineHeight: 1.2 }}>
              Lesson on {dateStr}
            </h2>
            {booking.instructor?.name && (
              <div style={{ fontSize: 13, color: 'oklch(54% 0.03 265)', marginTop: 4 }}>
                with {window.MASTERY?.maskTeacherName?.(booking.instructor.name) || booking.instructor.name}
              </div>
            )}
          </div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'oklch(55% 0.03 265)', fontSize: 24, lineHeight: 1 }}>×</button>
        </div>

        <div style={{ marginTop: 14, marginBottom: 16 }}>
          <SessionFeedbackStars value={rating} onChange={setRating} />
        </div>

        <textarea value={note} onChange={e => setNote(e.target.value)}
          placeholder="Anything you'd like to share? (optional)"
          rows={4}
          style={{
            width: '100%', padding: '12px 14px',
            border: '1.5px solid oklch(88% 0.01 265)', borderRadius: 10,
            fontFamily: "'Plus Jakarta Sans', sans-serif", fontSize: 14,
            resize: 'vertical', outline: 'none', lineHeight: 1.55, boxSizing: 'border-box',
          }} />

        {error && (
          <div style={{ background: 'oklch(96% 0.03 25)', color: 'oklch(40% 0.15 25)', padding: '10px 14px', borderRadius: 8, fontSize: 13, marginTop: 12 }}>
            {error}
          </div>
        )}

        <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
          <button onClick={onClose} style={{
            flex: 1, background: 'transparent', color: 'oklch(22% 0.06 265)',
            border: '1.5px solid oklch(82% 0.04 265)', borderRadius: 10, padding: '12px 0',
            fontWeight: 600, fontSize: 14, cursor: 'pointer',
            fontFamily: "'Plus Jakarta Sans', sans-serif",
          }}>Later</button>
          <button onClick={submit} disabled={busy} style={{
            flex: 2, background: 'oklch(22% 0.06 265)', color: '#fff',
            border: 'none', borderRadius: 10, padding: '12px 0',
            fontWeight: 700, fontSize: 14,
            cursor: busy ? 'wait' : 'pointer', opacity: busy ? 0.7 : 1,
            fontFamily: "'Plus Jakarta Sans', sans-serif",
          }}>{busy ? 'Submitting…' : 'Submit feedback'}</button>
        </div>
      </div>
    </div>
  );
};

window.StudentSessionFeedbackModal = StudentSessionFeedbackModal;

// ── Student-side banner ──────────────────────────────────────────────
// Drop me into student-home.jsx above the lesson list. I query unrated
// past lessons directly (rather than reading data.studentBookings) so
// this draft works without changes to dashboard-data.js. After merge,
// dashboard-data.js should also surface student_rating + student_rating_at
// on the booking objects and this component can switch to reading from
// the in-memory cache like the rest of student-home does.
const StudentSessionFeedbackBanner = () => {
  const auth = window.useAuth ? window.useAuth() : null;
  const userId = auth?.user?.id;
  const [unrated, setUnrated] = React.useState([]);
  const [active,  setActive]  = React.useState(null);
  const [thanks,  setThanks]  = React.useState(false);

  const load = React.useCallback(async () => {
    if (!userId) { setUnrated([]); return; }
    const { data, error } = await window.supa
      .from('bookings')
      .select('id, scheduled_at, duration_minutes, instructor:instructors(id, full_name)')
      .eq('student_id', userId)
      .eq('status', 'completed')
      .is('student_rating', null)
      .lt('scheduled_at', new Date().toISOString())
      .order('scheduled_at', { ascending: false })
      .limit(6);
    if (error) { setUnrated([]); return; }
    // Normalize to the shape the modal expects (camelCase scheduledAt +
    // instructor.name) so the modal can also be reused elsewhere with
    // already-camelCased rows.
    setUnrated((data || []).map(r => ({
      id: r.id,
      scheduledAt: r.scheduled_at,
      durationMinutes: r.duration_minutes,
      instructor: r.instructor ? { id: r.instructor.id, name: r.instructor.full_name } : null,
    })));
  }, [userId]);

  React.useEffect(() => { load(); }, [load]);

  if (!unrated.length && !thanks) return null;

  const fmt = (iso) => new Date(iso).toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' });

  return (
    <>
      <div style={{
        background: 'linear-gradient(135deg, oklch(96.5% 0.07 80) 0%, oklch(98% 0.03 80) 100%)',
        border: '1px solid oklch(86% 0.1 80)',
        borderRadius: 18, padding: '18px clamp(16px, 5vw, 22px)', marginBottom: 20,
      }}>
        <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'oklch(40% 0.13 75)', marginBottom: 6 }}>
          {unrated.length > 0 ? 'Quick feedback' : 'Thanks!'}
        </div>
        {unrated.length > 0 ? (
          <>
            <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 20, fontWeight: 600, color: 'oklch(22% 0.06 265)', lineHeight: 1.25, marginBottom: 4 }}>
              How {unrated.length === 1 ? 'was your last session?' : 'were your recent sessions?'}
            </div>
            <div style={{ fontSize: 13.5, color: 'oklch(44% 0.04 265)', lineHeight: 1.55, marginBottom: 14 }}>
              Takes 10 seconds. Helps your coach get better and helps us match future students well.
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {unrated.map(b => (
                <button key={b.id} onClick={() => setActive(b)} style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
                  background: '#fff', border: '1px solid oklch(90% 0.05 80)', borderRadius: 12,
                  padding: '11px 14px', cursor: 'pointer', textAlign: 'left',
                  fontFamily: "'Plus Jakarta Sans', sans-serif",
                }}>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: 'oklch(22% 0.06 265)', lineHeight: 1.2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {fmt(b.scheduledAt)}
                      {b.instructor?.name && (
                        <span style={{ color: 'oklch(54% 0.03 265)', fontWeight: 500 }}>
                          {' · '}{window.MASTERY?.maskTeacherName?.(b.instructor.name) || b.instructor.name}
                        </span>
                      )}
                    </div>
                    <div style={{ fontSize: 12, color: 'oklch(58% 0.03 265)', marginTop: 2 }}>
                      Tap to rate
                    </div>
                  </div>
                  <span style={{ fontSize: 18, color: 'oklch(40% 0.13 75)', fontWeight: 600, flexShrink: 0 }}>→</span>
                </button>
              ))}
            </div>
          </>
        ) : (
          <div style={{ fontSize: 14, color: 'oklch(36% 0.1 75)', lineHeight: 1.55 }}>
            Got it — thanks for letting us know.
          </div>
        )}
      </div>

      {active && (
        <StudentSessionFeedbackModal
          booking={active}
          onClose={() => setActive(null)}
          onSubmitted={() => { setThanks(true); load(); }}
        />
      )}
    </>
  );
};

window.StudentSessionFeedbackBanner = StudentSessionFeedbackBanner;

// ── Teacher-side rating control ──────────────────────────────────────
// Slots into LessonDetailPopup above the existing notes textarea. The
// teacher's note is already required + saved by instructor_save_notes;
// this control fires a separate RPC so we don't have to redefine the
// notes RPC just to add a number column. After merge we'd extend
// instructor_save_notes(p_rating int) and have this component become
// purely presentational.
const TeacherSessionRatingControl = ({ booking, onSaved }) => {
  const initial = booking?.teacherRating ?? booking?.teacher_rating ?? null;
  const [value, setValue] = React.useState(initial);
  const [busy,  setBusy]  = React.useState(false);
  const [error, setError] = React.useState(null);

  // If the popup gets re-opened on a different booking, reset.
  React.useEffect(() => {
    setValue(booking?.teacherRating ?? booking?.teacher_rating ?? null);
    setError(null);
  }, [booking?.id]);

  const pick = async (n) => {
    setValue(n); setError(null); setBusy(true);
    try {
      await window.Bookings.db.saveSessionRating(booking.id, n);
      if (onSaved) onSaved(n);
    } catch (e) {
      setError(e.message || 'Could not save');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid oklch(94% 0.005 60)' }}>
      <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'oklch(52% 0.04 265)', marginBottom: 8 }}>
        How was the session? <span style={{ fontWeight: 500, color: 'oklch(58% 0.03 265)', textTransform: 'none', letterSpacing: 0 }}>· admin-only</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        <SessionFeedbackStars value={value || 0} onChange={pick} size={26} />
        {busy && <span style={{ fontSize: 11, color: 'oklch(58% 0.03 265)' }}>Saving…</span>}
        {!busy && value && <span style={{ fontSize: 11, color: 'oklch(30% 0.13 150)', fontWeight: 600 }}>Saved</span>}
      </div>
      {error && (
        <div style={{ fontSize: 11, color: 'oklch(40% 0.15 25)', marginTop: 6 }}>{error}</div>
      )}
    </div>
  );
};

window.TeacherSessionRatingControl = TeacherSessionRatingControl;
