'use client';

import { useEffect, useRef, useState, useMemo } from 'react';
import { Loader2 } from 'lucide-react';
import { useHistoryStore } from '@/lib/store/history-store';
import { HistoryCard } from './HistoryCard';
import { EmptyHistoryState } from './EmptyHistoryState';
import type { Draft } from '@/lib/db/draft-service';

/**
 * Get ISO week number and year for a given date
 * Returns format: "W{week} - {year}"
 */
function getWeekLabel(date: Date): string {
  const d = new Date(date);
  // Set to nearest Thursday (current date + 4 - current day number)
  // Make Sunday's day number 7
  d.setDate(d.getDate() + 4 - (d.getDay() || 7));
  // Get first day of year
  const yearStart = new Date(d.getFullYear(), 0, 1);
  // Calculate full weeks to nearest Thursday
  const weekNo = Math.ceil((((d.getTime() - yearStart.getTime()) / 86400000) + 1) / 7);
  return `W${weekNo} - ${d.getFullYear()}`;
}

/**
 * Group drafts by week
 */
function groupDraftsByWeek(drafts: Draft[]): Map<string, Draft[]> {
  const groups = new Map<string, Draft[]>();

  drafts.forEach(draft => {
    const weekLabel = getWeekLabel(new Date(draft.createdAt));
    if (!groups.has(weekLabel)) {
      groups.set(weekLabel, []);
    }
    groups.get(weekLabel)!.push(draft);
  });

  return groups;
}

/**
 * HistoryFeed Component
 *
 * Story 3.1: List of completed drafts with lazy loading
 *
 * Features:
 * - Week-based grouping with headers (W36 - 2026)
 * - Lazy loading (infinite scroll)
 * - Loading spinner at bottom
 * - Empty state for new users
 * - Error state with retry
 * - Progressive fade-in for new items
 *
 * Architecture Compliance:
 * - Uses atomic selectors from HistoryStore
 * - Triggers loadMore when scrolling near bottom
 */
export function HistoryFeed() {
  const drafts = useHistoryStore((s) => s.drafts);
  const loading = useHistoryStore((s) => s.loading);
  const hasMore = useHistoryStore((s) => s.hasMore);
  const error = useHistoryStore((s) => s.error);
  const loadMore = useHistoryStore((s) => s.loadMore);
  const clearError = useHistoryStore((s) => s.clearError);

  const scrollContainerRef = useRef<HTMLDivElement>(null);
  const [initialLoad, setInitialLoad] = useState(true);

  // Group drafts by week
  const groupedDrafts = useMemo(() => groupDraftsByWeek(drafts), [drafts]);

  // Initial load on mount
  useEffect(() => {
    loadMore().finally(() => {
      setInitialLoad(false);
    });
  }, [loadMore]);

  // Infinite scroll handler
  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const target = e.target as HTMLDivElement;
    const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;

    // Trigger loadMore when 200px from bottom
    if (scrollBottom < 200 && hasMore && !loading && !error) {
      loadMore();
    }
  };

  const handleRetry = () => {
    clearError();
    loadMore();
  };

  const handleStartVent = () => {
    // Navigate to chat page
    window.location.href = '/chat';
  };

  // Empty state
  if (!initialLoad && drafts.length === 0 && !loading) {
    return <EmptyHistoryState onStartVent={handleStartVent} />;
  }

  return (
    <div className="history-feed flex flex-col h-full">
      {/* Scrollable feed container */}
      <div
        ref={scrollContainerRef}
        onScroll={handleScroll}
        className="flex-1 overflow-y-auto px-4 py-4"
      >
        {/* Render grouped drafts by week */}
        {Array.from(groupedDrafts.entries()).map(([weekLabel, weekDrafts]) => (
          <div key={weekLabel} className="mb-6">
            {/* Week separator header */}
            <div className="flex items-center justify-center gap-3 mt-6 mb-4">
              <div className="h-px flex-1 max-w-[100px] bg-border" />
              <span className="text-xs font-medium text-muted-foreground uppercase tracking-wide px-3 py-1 bg-muted rounded-full border border-border">
                {weekLabel}
              </span>
              <div className="h-px flex-1 max-w-[100px] bg-border" />
            </div>

            {/* Drafts for this week */}
            <div className="space-y-3">
              {weekDrafts.map((draft) => (
                <HistoryCard
                  key={draft.id}
                  draft={draft}
                  onClick={(draft) => useHistoryStore.getState().selectDraft(draft)}
                />
              ))}
            </div>
          </div>
        ))}

        {/* Loading indicator at bottom */}
        {loading && (
          <div className="flex justify-center py-4">
            <Loader2 className="w-6 h-6 text-slate-400 animate-spin" aria-hidden="true" />
            <span className="sr-only">Loading more entries...</span>
          </div>
        )}

        {/* Error state with retry */}
        {error && (
          <div className="flex flex-col items-center py-4 px-6 bg-red-50 rounded-lg border border-red-200">
            <p className="text-red-700 mb-2">{error}</p>
            <button
              onClick={handleRetry}
              type="button"
              className="min-h-[44px] px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
            >
              Retry
            </button>
          </div>
        )}

        {/* End of list message */}
        {!hasMore && drafts.length > 0 && !loading && (
          <p className="text-center text-slate-500 py-4 font-sans">
            You've reached the beginning
          </p>
        )}
      </div>
    </div>
  );
}
