import { useEffect, useState, useCallback, useRef } from 'react';
import { useParams } from 'react-router-dom';
import { SearchApi } from '../api/client.js';

const FOLDER_META = {
  inbox:      { icon: '📥', label: 'Inbox' },
  allmail:    { icon: '📬', label: 'All Mail' },
  unread:     { icon: '🔵', label: 'Unread' },
  starred:    { icon: '⭐', label: 'Starred' },
  sent:       { icon: '📤', label: 'Sent' },
  drafts:     { icon: '✏️',  label: 'Drafts' },
  archive:    { icon: '📦', label: 'Archive' },
  spam:       { icon: '🚫', label: 'Spam' },
  trash:      { icon: '🗑️',  label: 'Trash' },
  unlabeled:  { icon: '🏷️',  label: 'Unlabeled' },
  pinned:     { icon: '📌', label: 'Pinned' },
  readlater:  { icon: '🔖', label: 'Read Later' },
  large:      { icon: '📎', label: 'Large Mail' },
  old:        { icon: '🕰️',  label: 'Old Mail' },
  automated:  { icon: '🤖', label: 'Automated' },
  noreply:    { icon: '🔇', label: 'No-Reply' },
  shopping:   { icon: '🛍️',  label: 'Online Shopping' },
  gaming:     { icon: '🎮', label: 'Gaming' },
  finance:    { icon: '💳', label: 'Finance & Insurance' },
  sales:      { icon: '🏷️',  label: 'Seasonal Sales' },
  ridesharing:{ icon: '🚗', label: 'Ride Sharing' },
  food:       { icon: '🍕', label: 'Food Delivery' },
  social:     { icon: '📱', label: 'Social Notifications' },
  wellness:   { icon: '🏃', label: 'Wellness & Sport' },
};

const PAGE_SIZE = 50;

const fmtDate = (iso) => {
  const d = new Date(iso);
  const now = new Date();
  const diffDays = (now - d) / 86400000;
  if (diffDays < 1) return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  if (diffDays < 7) return d.toLocaleDateString([], { weekday: 'short' });
  return d.toLocaleDateString([], { month: 'short', day: 'numeric' });
};

const fmtSize = (b) => {
  if (b < 1024) return `${b} B`;
  if (b < 1048576) return `${(b / 1024).toFixed(0)} KB`;
  return `${(b / 1048576).toFixed(1)} MB`;
};

export default function FolderView() {
  const { slug } = useParams();
  const meta = FOLDER_META[slug] ?? { icon: '📁', label: slug };

  const [emails, setEmails] = useState([]);
  const [totalCount, setTotalCount] = useState(null);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // Reset when the folder changes
  useEffect(() => {
    setEmails([]);
    setTotalCount(null);
    setPage(1);
    setHasMore(true);
    setError(null);
  }, [slug]);

  // Fetch a page and append results
  const fetchPage = useCallback((p) => {
    setLoading(true);
    SearchApi.folder(slug, p, PAGE_SIZE)
      .then((r) => {
        setEmails((prev) => p === 1 ? r.items : [...prev, ...r.items]);
        setTotalCount(r.totalCount);
        setHasMore(p < r.totalPages);
        setPage(p);
      })
      .catch(() => setError('Failed to load emails.'))
      .finally(() => setLoading(false));
  }, [slug]);

  // Initial load
  useEffect(() => { fetchPage(1); }, [fetchPage]);

  // Sentinel div observed to trigger next page
  const sentinelRef = useRef(null);
  useEffect(() => {
    const el = sentinelRef.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && hasMore && !loading) {
          fetchPage(page + 1);
        }
      },
      { rootMargin: '200px' }
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, [hasMore, loading, page, fetchPage]);

  return (
    <div className="folder-view">
      <div className="folder-view-head">
        <h2 className="folder-view-title">{meta.icon} {meta.label}</h2>
        {totalCount !== null && (
          <span className="folder-view-count">{totalCount.toLocaleString()} email{totalCount !== 1 ? 's' : ''}</span>
        )}
      </div>

      {error && <div className="fv-error">{error}</div>}

      {!loading && !error && emails.length === 0 && (
        <div className="fv-empty">No emails in this folder.</div>
      )}

      {emails.length > 0 && (
        <table className="email-list">
          <tbody>
            {emails.map((e) => (
              <tr key={e.id} className={`email-row${e.isUnread ? ' email-row--unread' : ''}`}>
                <td className="el-unread">{e.isUnread && <span className="unread-dot" />}</td>
                <td className="el-sender" title={e.senderAddress}>
                  {e.senderDisplayName || e.senderAddress}
                </td>
                <td className="el-subject">
                  <span className="el-subj-text">{e.subject || '(no subject)'}</span>
                  {e.snippet && <span className="el-snippet"> — {e.snippet}</span>}
                </td>
                <td className="el-meta">
                  {e.hasAttachments && <span className="el-attach" title="Has attachment">📎</span>}
                  {e.sizeEstimateBytes > 1048576 && <span className="el-size">{fmtSize(e.sizeEstimateBytes)}</span>}
                </td>
                <td className="el-date">{fmtDate(e.sentAtUtc)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      )}

      {/* Sentinel — triggers next page load when scrolled into view */}
      <div ref={sentinelRef} className="fv-sentinel" />

      {loading && <div className="fv-loading-more">Loading…</div>}
      {!hasMore && emails.length > 0 && (
        <div className="fv-end">— {emails.length.toLocaleString()} emails —</div>
      )}
    </div>
  );
}
