/* global React, Icon, Avatar, ChannelIcon, ChannelDot, StageChip */
const { useState, useEffect, useMemo } = React;

const CHANNEL_TYPE_TO_KIND = {
  LINKEDIN: 'linkedin',
  WHATSAPP: 'whatsapp',
  INSTAGRAM: 'instagram',
  GOOGLE_OAUTH: 'email',
  GOOGLE: 'email',
  OUTLOOK: 'email',
  IMAP: 'email',
};

function relativeTime(iso) {
  if (!iso) return '';
  const d = new Date(iso);
  const diff = (Date.now() - d.getTime()) / 1000;
  if (diff < 60) return 'now';
  if (diff < 3600) return `${Math.round(diff / 60)}m`;
  if (diff < 86400) return `${Math.round(diff / 3600)}h`;
  if (diff < 86400 * 7) return `${Math.round(diff / 86400)}d`;
  return d.toLocaleDateString();
}

function colorFromString(s) {
  const palette = ['#22c55e', '#3b82f6', '#a855f7', '#f97316', '#eab308', '#ec4899', '#06b6d4', '#84cc16'];
  let h = 0;
  for (let i = 0; i < (s || '').length; i++) h = ((h << 5) - h) + s.charCodeAt(i);
  return palette[Math.abs(h) % palette.length];
}

function api(path, opts = {}) {
  return fetch(path, { credentials: 'include', ...opts }).then(async (r) => {
    if (r.status === 401) {
      window.location.href = '/login.html?next=' + encodeURIComponent(window.location.pathname);
      return null;
    }
    if (!r.ok) throw new Error(`${r.status} ${r.statusText}`);
    return r.json();
  });
}

function Inbox({ goto }) {
  const [threads, setThreads] = useState(null);
  const [activeId, setActiveId] = useState(null);
  const [filter, setFilter] = useState('all');
  const [activeMessages, setActiveMessages] = useState([]);
  const [composer, setComposer] = useState('');
  const [sending, setSending] = useState(false);
  const [sendError, setSendError] = useState(null);
  const [error, setError] = useState(null);

  const reloadThreads = () => api('/api/messages/threads?limit=100').then((d) => {
    if (!d) return;
    setThreads(d.items || []);
    if ((d.items || []).length > 0 && !activeId) setActiveId(d.items[0].id);
  });

  useEffect(() => {
    reloadThreads().catch((e) => setError(e.message));
  }, []);

  const reloadActiveMessages = (threadKey) => {
    if (!threadKey) {
      setActiveMessages([]);
      return Promise.resolve();
    }
    return api(`/api/messages?thread_id=${encodeURIComponent(threadKey)}&limit=200`)
      .then((d) => d && setActiveMessages(d.items || []))
      .catch(() => setActiveMessages([]));
  };

  useEffect(() => {
    if (!activeId || !threads) return;
    const active = threads.find((t) => t.id === activeId);
    if (!active || !active.thread_id) {
      setActiveMessages([]);
      return;
    }
    reloadActiveMessages(active.thread_id);
  }, [activeId, threads]);

  const handleSend = async () => {
    const active = threads?.find((t) => t.id === activeId);
    if (!active || !active.thread_id || !composer.trim()) return;
    setSending(true);
    setSendError(null);
    try {
      const res = await fetch('/api/messages/send', {
        method: 'POST',
        credentials: 'include',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ thread_id: active.thread_id, text: composer.trim() }),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.detail || `${res.status} ${res.statusText}`);
      }
      setComposer('');
      await reloadActiveMessages(active.thread_id);
      await reloadThreads();
    } catch (e) {
      setSendError(e.message || 'Send failed');
    } finally {
      setSending(false);
    }
  };

  const filtered = useMemo(() => {
    if (!threads) return [];
    if (filter === 'all') return threads;
    return threads.filter((t) => CHANNEL_TYPE_TO_KIND[t.channel_type] === filter);
  }, [threads, filter]);

  const active = threads ? threads.find((t) => t.id === activeId) : null;
  const activeKind = active ? CHANNEL_TYPE_TO_KIND[active.channel_type] || 'email' : null;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr 320px', height: '100%', overflow: 'hidden' }}>
      {/* Thread list */}
      <div style={{ borderRight: '1px solid var(--divider)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <div style={{ padding: '14px 16px 12px', borderBottom: '1px solid var(--divider)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
            <h2 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 800, fontSize: 20, margin: 0, letterSpacing: '-0.02em' }}>Inbox</h2>
            <span className="mono" style={{ fontSize: 11, color: 'var(--text-dim)' }}>{threads ? `${threads.length} threads` : '…'}</span>
          </div>
          <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
            {[
              { id: 'all', label: 'All' },
              { id: 'linkedin', label: 'LinkedIn', kind: 'linkedin' },
              { id: 'whatsapp', label: 'WhatsApp', kind: 'whatsapp' },
              { id: 'instagram', label: 'IG', kind: 'instagram' },
              { id: 'email', label: 'Email', kind: 'email' },
            ].map((f) => (
              <button
                key={f.id}
                onClick={() => setFilter(f.id)}
                className="btn btn-sm"
                style={{
                  padding: '4px 8px',
                  background: filter === f.id ? 'var(--raised)' : 'transparent',
                  borderColor: filter === f.id ? 'var(--divider-strong)' : 'var(--divider)',
                  color: filter === f.id ? 'var(--text)' : 'var(--text-secondary)',
                  display: 'flex', alignItems: 'center', gap: 4,
                }}
              >
                {f.kind && <ChannelIcon kind={f.kind} size={10} />}
                {f.label}
              </button>
            ))}
          </div>
        </div>
        <div style={{ flex: 1, overflowY: 'auto' }}>
          {threads === null && (
            <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-dim)', fontSize: 12 }}>Loading…</div>
          )}
          {threads !== null && filtered.length === 0 && (
            <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-dim)', fontSize: 12, lineHeight: 1.6 }}>
              {threads.length === 0
                ? 'No conversations yet. Send yourself a message on LinkedIn, WhatsApp or Gmail to test.'
                : 'No messages match this filter'}
              {error && <div style={{ marginTop: 12, color: 'var(--red)' }}>{error}</div>}
            </div>
          )}
          {filtered.map((t) => {
            const kind = CHANNEL_TYPE_TO_KIND[t.channel_type] || 'email';
            const isActive = t.id === activeId;
            const name = t.contact_name || t.sender_handle || '(unknown)';
            const initials = t.contact_avatar_initials || '?';
            const color = colorFromString(name);
            return (
              <div key={t.id} onClick={() => setActiveId(t.id)}
                style={{
                  padding: '12px 16px', borderBottom: '1px solid var(--divider)', cursor: 'pointer',
                  display: 'flex', alignItems: 'flex-start', gap: 10, position: 'relative',
                  background: isActive ? 'var(--raised)' : 'transparent',
                }}>
                {isActive && <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 2, background: 'var(--accent)' }}></div>}
                <div style={{ position: 'relative', flexShrink: 0 }}>
                  <Avatar name={name} initials={initials} color={color} size="md" />
                  <div style={{ position: 'absolute', bottom: -2, right: -2 }}>
                    <ChannelDot kind={kind} />
                  </div>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <span style={{ fontWeight: 500, color: 'var(--text)', fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{name}</span>
                    <span className="mono" style={{ fontSize: 10, color: 'var(--text-dim)', marginLeft: 'auto', flexShrink: 0 }}>{relativeTime(t.received_at)}</span>
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--text-dim)', marginBottom: 4, textTransform: 'capitalize' }}>{kind} · {t.message_count} message{t.message_count === 1 ? '' : 's'}</div>
                  <div style={{ fontSize: 12, color: 'var(--text-dim)', overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>
                    {t.preview}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Thread view */}
      <div style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        {!active && (
          <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-dim)', fontSize: 13 }}>
            Select a conversation
          </div>
        )}
        {active && (
          <>
            <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 12 }}>
              <Avatar name={active.contact_name || active.sender_handle} initials={active.contact_avatar_initials} color={colorFromString(active.contact_name || active.sender_handle)} size="md" />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontWeight: 600, color: 'var(--text)' }}>{active.contact_name || active.sender_handle}</span>
                  <ChannelIcon kind={activeKind} size={12} />
                  <span style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'capitalize' }}>· {activeKind}</span>
                </div>
                <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>via {active.channel_name}</div>
              </div>
              {active.contact_id && (
                <button className="btn btn-ghost btn-icon" onClick={() => goto('contact', active.contact_id)} title="Open contact">
                  <Icon name="external" size={14} />
                </button>
              )}
            </div>

            <div style={{ flex: 1, overflowY: 'auto', padding: 20, display: 'flex', flexDirection: 'column', gap: 12 }}>
              {activeMessages.length === 0 && (
                <div style={{ textAlign: 'center', color: 'var(--text-dim)', fontSize: 12, padding: 40 }}>Loading messages…</div>
              )}
              {activeMessages.map((m) => (
                <div key={m.id} style={{ display: 'flex', justifyContent: m.direction === 'out' ? 'flex-end' : 'flex-start' }}>
                  <div style={{ maxWidth: '70%' }}>
                    {m.subject && (
                      <div style={{ fontSize: 11, color: 'var(--text-dim)', marginBottom: 4, fontWeight: 600 }}>Subject: {m.subject}</div>
                    )}
                    <div style={{
                      padding: '10px 14px',
                      background: m.direction === 'out' ? 'var(--accent-bg)' : 'var(--surface)',
                      border: '1px solid',
                      borderColor: m.direction === 'out' ? 'rgba(34,197,94,0.25)' : 'var(--divider)',
                      fontSize: 13,
                      color: 'var(--text)',
                      whiteSpace: 'pre-wrap',
                      lineHeight: 1.55,
                    }}>
                      {m.text}
                    </div>
                    <div style={{ fontSize: 10, color: 'var(--text-dim)', marginTop: 4, textAlign: m.direction === 'out' ? 'right' : 'left' }} className="mono">{relativeTime(m.received_at)}</div>
                  </div>
                </div>
              ))}
            </div>

            {/* Composer */}
            <div style={{ borderTop: '1px solid var(--divider)', padding: 14 }}>
              <div style={{ background: 'var(--surface)', border: '1px solid var(--divider)', padding: 10 }}>
                <textarea
                  className="textarea"
                  placeholder={activeKind === 'email' ? 'Email reply not yet supported (Phase 2)' : `Reply on ${activeKind}…`}
                  value={composer}
                  onChange={(e) => setComposer(e.target.value)}
                  disabled={sending || activeKind === 'email'}
                  style={{ background: 'transparent', border: 'none', minHeight: 50, padding: 0, width: '100%', color: 'var(--text)', fontFamily: 'var(--font-body)', fontSize: 13 }}
                  onKeyDown={(e) => {
                    if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
                      handleSend();
                    }
                  }}
                />
                {sendError && (
                  <div style={{ fontSize: 11, color: 'var(--red)', marginTop: 6 }}>{sendError}</div>
                )}
                <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 8 }}>
                  <div style={{ flex: 1, fontSize: 11, color: 'var(--text-dim)' }}>
                    {activeKind === 'email' ? 'Email send wires up in Phase 2' : 'Cmd+Enter to send'}
                  </div>
                  <button
                    className="btn btn-primary btn-sm"
                    disabled={sending || !composer.trim() || activeKind === 'email'}
                    onClick={handleSend}
                  >
                    <Icon name="send" size={11} /> {sending ? 'Sending…' : 'Send'}
                  </button>
                </div>
              </div>
            </div>
          </>
        )}
      </div>

      {/* Contact panel (minimal until contacts wiring lands) */}
      <div style={{ borderLeft: '1px solid var(--divider)', overflowY: 'auto' }}>
        {active && (
          <div style={{ padding: 20, display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 8 }}>
            <Avatar name={active.contact_name || active.sender_handle} initials={active.contact_avatar_initials} color={colorFromString(active.contact_name || active.sender_handle)} size="xl" />
            <div>
              <div style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 700, fontSize: 18, marginTop: 6 }}>{active.contact_name || active.sender_handle}</div>
              <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 2 }}>{activeKind}</div>
            </div>
            {active.contact_id && (
              <button className="btn btn-sm" style={{ marginTop: 4 }} onClick={() => goto('contact', active.contact_id)}>
                Open Contact <Icon name="arrowRight" size={11} />
              </button>
            )}
            <div style={{ marginTop: 16, padding: '10px 14px', background: 'var(--surface)', border: '1px solid var(--divider)', fontSize: 11, color: 'var(--text-dim)', textAlign: 'left', width: '100%' }}>
              Pipeline stage, deal info, and activity timeline will populate here once the pipeline + deals layer is wired (next phase).
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Inbox });
