import { useEffect, useState, useCallback, useRef } from 'react';
import { useParams } from 'react-router-dom';
import { SearchApi } from '../api/client.js';
import EmailRow from '../components/EmailRow.jsx';
import EmailDetail from '../components/EmailDetail.jsx';
import BulkToolbar from '../components/BulkToolbar.jsx';
import { Skeleton, EmptyState } from '../components/ui';
import useSelection from '../hooks/useSelection.js';
import useListKeyboardNav from '../hooks/useListKeyboardNav.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;

function ListSkeleton({ rows = 6 }) {
  return (
    <div className="sv-skeleton-list" aria-hidden="true">
      {Array.from({ length: rows }).map((_, i) => (
        <div className="sv-skeleton-row" key={i}>
          <Skeleton className="h-3 w-3 rounded-full" />
          <Skeleton className="h-3 flex-1" />
          <Skeleton className="h-3 w-16" />
        </div>
      ))}
    </div>
  );
}


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);
  const [selectedEmail, setSelectedEmail] = useState(null);
  const { selected, toggle, clear, removeIds, selectedIds } = useSelection();
  const focusedId = useListKeyboardNav(emails, (id) => setEmails((prev) => prev.filter((x) => x.id !== id)));

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

  // 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>}

      <BulkToolbar
        selectedIds={selectedIds}
        onClear={clear}
        onDone={(action, ids) => {
          if (action === 'trash' || action === 'archive') {
            setEmails((prev) => prev.filter((x) => !ids.includes(x.id)));
            removeIds(ids);
          }
        }}
      />

      <div className={`sv-split${selectedEmail ? ' sv-split--open' : ''}`}>
        <div className="sv-list-pane">
          {loading && emails.length === 0 && !error && <ListSkeleton />}

          {!loading && !error && emails.length === 0 && (
            <EmptyState
              title="No emails in this folder"
              description="Nothing here yet — try another folder or run a sync."
            />
          )}

          {emails.length > 0 && (
            <table className="email-list">
              <tbody>
                {emails.map((e) => (
                  <EmailRow
                    key={e.id}
                    email={e}
                    selected={selected.has(e.id)}
                    onToggleSelect={toggle}
                    focused={focusedId === e.id}
                    onOpen={(email) => setSelectedEmail(email)}
                    onRemove={(id) => {
                      setEmails((prev) => prev.filter((x) => x.id !== id));
                      setSelectedEmail((cur) => (cur?.id === id ? null : cur));
                    }}
                  />
                ))}
              </tbody>
            </table>
          )}

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

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

        {selectedEmail && (
          <aside className="sv-reading-pane">
            <EmailDetail
              key={selectedEmail.id}
              email={selectedEmail}
              onClose={() => setSelectedEmail(null)}
            />
          </aside>
        )}
      </div>
    </div>
  );
}
