"use client";

import { useState, useEffect } from "react";
import { AppShell } from "@/components/AppShell";
import { WeeklyReflection } from "@/components/WeeklyReflection";
import { FilterPanel } from "@/components/FilterPanel";
import { EntryRow } from "@/components/EntryRow";
import { Loader2 } from "lucide-react";
import type { EntryWithTags, FilterState } from "@/lib/types";
import { APP_NAME } from "@/lib/constants";

export default function TimelinePage() {
  const [entries, setEntries] = useState<EntryWithTags[]>([]);
  const [filteredEntries, setFilteredEntries] = useState<EntryWithTags[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [filters, setFilters] = useState<FilterState>({
    moods: [],
    tagId: null,
    roughDay: null,
  });

  useEffect(() => {
    async function loadEntries() {
      try {
        const res = await fetch("/api/entries");
        if (res.ok) {
          setEntries(await res.json());
        }
      } catch (error) {
        console.error("Failed to load entries:", error);
      } finally {
        setIsLoading(false);
      }
    }
    loadEntries();
  }, []);

  // Apply filters client-side
  useEffect(() => {
    let result = entries;

    if (filters.moods.length > 0) {
      result = result.filter((e) => e.mood && filters.moods.includes(e.mood));
    }

    if (filters.tagId) {
      result = result.filter((e) => e.tags.some((t) => t.id === filters.tagId));
    }

    if (filters.roughDay === true) {
      result = result.filter((e) => e.roughDay);
    } else if (filters.roughDay === false) {
      result = result.filter((e) => !e.roughDay);
    }

    setFilteredEntries(result);
  }, [entries, filters]);

  return (
    <AppShell>
      <header className="mb-6">
        <h1 className="text-2xl font-light">{APP_NAME}</h1>
        <p className="text-sm text-muted">Timeline</p>
      </header>

      {isLoading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="animate-spin text-muted" size={24} />
        </div>
      ) : (
        <>
          <WeeklyReflection entries={entries} />
          <FilterPanel filters={filters} onChange={setFilters} />

          {filteredEntries.length === 0 ? (
            <div className="text-center py-12 text-muted">
              {entries.length === 0 ? (
                <p>No entries yet. Start your first check-in!</p>
              ) : (
                <p>No entries match your filters.</p>
              )}
            </div>
          ) : (
            <div className="space-y-3">
              {filteredEntries.map((entry) => (
                <EntryRow key={entry.id} entry={entry} />
              ))}
            </div>
          )}
        </>
      )}
    </AppShell>
  );
}
