// Team dashboard — configure interview slots and view bookings.

function slotLabel(slot) {
  return `${slot.day || slot.date} · ${slot.time}`;
}

function InterviewSlots({ useLive, data }) {
  const [slots, setSlots] = React.useState(() => WWAdmin.DEFAULT_INTERVIEW_SLOTS.map((s) => ({ ...s })));
  const [bookings, setBookings] = React.useState([]);
  const [loading, setLoading] = React.useState(!!useLive);
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');
  const [notice, setNotice] = React.useState('');
  const [form, setForm] = React.useState({ date: '', time: '10:00', capacity: 1 });

  const applicantByDbId = React.useMemo(() => {
    const map = {};
    (data || []).forEach((a) => { if (a.dbId) map[a.dbId] = a; });
    return map;
  }, [data]);

  const bookingCounts = React.useMemo(() => {
    const counts = {};
    bookings.forEach((b) => {
      const id = b.payload?.slot?.id;
      if (id) counts[id] = (counts[id] || 0) + 1;
    });
    return counts;
  }, [bookings]);

  const load = React.useCallback(async () => {
    if (!useLive) {
      setLoading(false);
      return;
    }
    try {
      const [slotRows, bookingRows] = await Promise.all([
        WWAdmin.fetchInterviewSlots(),
        WWAdmin.fetchInterviewBookings(),
      ]);
      setSlots(slotRows);
      setBookings(bookingRows);
    } catch (err) {
      setError(err.message || 'Could not load interview slots.');
    } finally {
      setLoading(false);
    }
  }, [useLive]);

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

  React.useEffect(() => {
    if (!useLive) return undefined;
    const timer = setInterval(load, 30000);
    return () => clearInterval(timer);
  }, [useLive, load]);

  const formatDay = (isoDate) => {
    const d = new Date(isoDate + 'T12:00:00');
    return d.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
  };

  const handleAddSlot = async (e) => {
    e?.preventDefault();
    setError('');
    setNotice('');
    if (!form.date || !form.time) {
      setError('Pick a date and time.');
      return;
    }
    const next = {
      id: `slot-${Date.now()}`,
      date: form.date,
      day: formatDay(form.date),
      time: form.time,
      capacity: Math.max(1, parseInt(form.capacity, 10) || 1),
    };
    const updated = [...slots, next];
    setSlots(updated);
    if (useLive) {
      setSaving(true);
      try {
        await WWAdmin.saveInterviewSlots(updated);
        setNotice('Interview slot added.');
        setForm({ date: '', time: '10:00', capacity: 1 });
        await load();
      } catch (err) {
        setError(err.message || 'Save failed.');
        setSlots(slots);
      } finally {
        setSaving(false);
      }
    }
  };

  const handleRemoveSlot = async (id) => {
    if ((bookingCounts[id] || 0) > 0) {
      setError('Cannot remove a slot that already has a booking.');
      return;
    }
    if (!confirm('Remove this interview slot?')) return;
    setError('');
    const updated = slots.filter((s) => s.id !== id);
    setSlots(updated);
    if (useLive) {
      try {
        await WWAdmin.saveInterviewSlots(updated);
        setNotice('Slot removed.');
        await load();
      } catch (err) {
        setError(err.message || 'Could not remove slot.');
        await load();
      }
    }
  };

  const bookedApplicants = bookings.map((b) => {
    const cand = applicantByDbId[b.applicant_id];
    const joined = b.applicants;
    const slot = b.payload?.slot;
    return {
      name: joined?.name || cand?.name || 'Unknown applicant',
      email: joined?.email || cand?.email || '—',
      refId: joined?.ref_id || cand?.id || '—',
      slotLabel: slot ? `${slot.day || slot.date} · ${slot.time}` : '—',
      submittedAt: b.submitted_at,
    };
  });

  return (
    <div style={{ padding: '30px 36px 48px' }}>
      <Eyebrow>Final stage</Eyebrow>
      <h1 style={{ fontFamily: DISP, fontWeight: 600, fontSize: 34, letterSpacing: '-0.02em', margin: '8px 0 6px' }}>Interview slots</h1>
      <p style={{ fontSize: 15, color: T.muted, lineHeight: 1.55, maxWidth: 620, marginBottom: 24 }}>
        Add dates and times shortlisted applicants can book. Slots mark as full when capacity is reached.
      </p>

      {error && (
        <Card pad={14} style={{ marginBottom: 16, background: T.redSoft, border: 'none' }}>
          <div style={{ fontSize: 13, color: T.red }}>{error}</div>
        </Card>
      )}
      {notice && (
        <Card pad={14} style={{ marginBottom: 16, background: T.greenSoft, border: 'none' }}>
          <div style={{ fontSize: 13, color: T.green }}>{notice}</div>
        </Card>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 20 }}>
        <Card pad={22}>
          <Eyebrow style={{ marginBottom: 14 }}>Add slot</Eyebrow>
          <form onSubmit={handleAddSlot}>
            <label style={{ display: 'block', marginBottom: 14 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: T.muted, marginBottom: 7 }}>Date</div>
              <input type="date" value={form.date} onChange={(e) => setForm((f) => ({ ...f, date: e.target.value }))} required
                style={{ width: '100%', height: 44, borderRadius: 12, border: `1px solid ${T.lineStrong}`, padding: '0 14px', fontFamily: FONT, boxSizing: 'border-box' }} />
            </label>
            <label style={{ display: 'block', marginBottom: 14 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: T.muted, marginBottom: 7 }}>Time</div>
              <input type="time" value={form.time} onChange={(e) => setForm((f) => ({ ...f, time: e.target.value }))} required
                style={{ width: '100%', height: 44, borderRadius: 12, border: `1px solid ${T.lineStrong}`, padding: '0 14px', fontFamily: FONT, boxSizing: 'border-box' }} />
            </label>
            <label style={{ display: 'block', marginBottom: 18 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: T.muted, marginBottom: 7 }}>Capacity</div>
              <input type="number" min={1} max={10} value={form.capacity} onChange={(e) => setForm((f) => ({ ...f, capacity: e.target.value }))}
                style={{ width: 100, height: 44, borderRadius: 12, border: `1px solid ${T.lineStrong}`, padding: '0 14px', fontFamily: FONT }} />
            </label>
            <Btn variant="primary" type="submit" icon="clock" disabled={saving}>{saving ? 'Saving…' : 'Add slot'}</Btn>
          </form>
        </Card>

        <Card pad={22}>
          <Eyebrow style={{ marginBottom: 14 }}>Bookings ({bookedApplicants.length})</Eyebrow>
          {bookedApplicants.length === 0 ? (
            <div style={{ fontSize: 14, color: T.muted, lineHeight: 1.5 }}>No interviews booked yet. Shortlist candidates to unlock scheduling for them.</div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxHeight: 280, overflowY: 'auto' }}>
              {bookedApplicants.map((b, i) => (
                <div key={i} style={{ padding: '12px 14px', borderRadius: 12, background: T.panel }}>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{b.name}</div>
                  <div style={{ fontSize: 12.5, color: T.subtle, marginTop: 2 }}>{b.refId} · {b.email}</div>
                  <div style={{ fontSize: 13, color: T.muted, marginTop: 4 }}>{b.slotLabel}</div>
                </div>
              ))}
            </div>
          )}
        </Card>
      </div>

      <Card pad={0} style={{ overflow: 'hidden' }}>
        <div style={{ padding: '18px 22px', borderBottom: `1px solid ${T.line}` }}>
          <Eyebrow>Available slots ({slots.length})</Eyebrow>
          {loading && <span style={{ fontSize: 13, color: T.muted, marginLeft: 12 }}>Loading…</span>}
        </div>
        {slots.length === 0 ? (
          <div style={{ padding: 32, textAlign: 'center', color: T.muted }}>No slots configured.</div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ borderBottom: `1px solid ${T.line}`, background: T.panel }}>
                <th style={{ textAlign: 'left', padding: '12px 22px', fontSize: 12, color: T.muted }}>When</th>
                <th style={{ textAlign: 'left', padding: '12px 16px', fontSize: 12, color: T.muted }}>Capacity</th>
                <th style={{ textAlign: 'left', padding: '12px 16px', fontSize: 12, color: T.muted }}>Booked</th>
                <th style={{ width: 100 }} />
              </tr>
            </thead>
            <tbody>
              {slots.map((slot) => {
                const booked = bookingCounts[slot.id] || 0;
                const full = booked >= (slot.capacity || 1);
                return (
                  <tr key={slot.id} style={{ borderBottom: `1px solid ${T.line}` }}>
                    <td style={{ padding: '14px 22px', fontSize: 14.5, fontWeight: 600 }}>{slotLabel(slot)}</td>
                    <td style={{ padding: '14px 16px', fontSize: 14 }}>{slot.capacity || 1}</td>
                    <td style={{ padding: '14px 16px' }}>
                      <Badge status={full ? 'rejected' : booked > 0 ? 'shortlist' : 'in_review'} size="sm" />
                      <span style={{ marginLeft: 8, fontSize: 13, color: T.muted }}>{booked} / {slot.capacity || 1}{full ? ' · Full' : ''}</span>
                    </td>
                    <td style={{ padding: '14px 16px', textAlign: 'right' }}>
                      <Btn variant="ghost" size="sm" onClick={() => handleRemoveSlot(slot.id)} disabled={booked > 0}>Remove</Btn>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </Card>
    </div>
  );
}

Object.assign(window, { InterviewSlots });
