import { useLiveQuery } from "dexie-react-hooks";
import { History as HistoryIcon } from "lucide-react";
import { db } from "../database/db";
import { useAllGames } from "../games";
import { PageHeader } from "../components/PageHeader";
import { SessionCard } from "../components/SessionCard";
import { useProfileStore } from "../stores/profileStore";

export default function History() {
  const activeProfileId = useProfileStore((s) => s.activeProfileId);
  const games = useAllGames();
  const sessions = useLiveQuery(
    async () => {
      if (!activeProfileId) return [];
      const arr = await db.sessions
        .where("profileId")
        .equals(activeProfileId)
        .and((s) => !s.deletedAt)
        .sortBy("dateStart");
      return arr.reverse();
    },
    [activeProfileId],
  );
  const locations = useLiveQuery(() => db.locations.toArray()) || [];

  return (
    <div className="p-5 space-y-5 relative z-10">
      <PageHeader title="Parties" />

      {!sessions || sessions.length === 0 ? (
        <div className="text-center text-muted-foreground py-14 bg-card/50 backdrop-blur-sm rounded-[1.75rem] border border-black/5 dark:border-white/10">
          <HistoryIcon className="w-12 h-12 mx-auto mb-3 opacity-20" />
          <p className="font-bold">Aucune partie enregistrée.</p>
          <p className="text-sm mt-1">Lancez une partie depuis l'accueil.</p>
        </div>
      ) : (
        <div className="space-y-3">
          {sessions.map((session) => {
            const game = games.find((g) => g.id === session.gameId);
            if (!game) return null;
            const location = session.locationId
              ? locations.find((l) => l.id === session.locationId)
              : undefined;
            return (
              <SessionCard
                key={session.id}
                session={session}
                game={game}
                location={location}
              />
            );
          })}
        </div>
      )}
    </div>
  );
}
