"use client";

import { useRouter } from "next/navigation";
import { useTransition, useEffect } from "react";
import { deleteDraft } from "@/data/drafts/actions";
import { HomeWalkingPill } from "../walking/HomeWalkingPill";
import { HomeEmptyState } from "@/app/HomeEmptyState";
import type { DraftListItem } from "@/data/drafts/queries";

type Props = {
  initialDrafts: DraftListItem[];
};

export function DraftsClientPage({ initialDrafts }: Props) {
  const router = useRouter();
  const [, startTransition] = useTransition();

  // With Cache Components + Activity, effects are recreated when page becomes visible.
  // Refresh data on every activation to ensure freshness.
  useEffect(() => {
    startTransition(() => {
      router.refresh();
    });
  }, [router, startTransition]);

  const handleDelete = async (rkey: string) => {
    await deleteDraft(rkey);
    startTransition(() => {
      router.refresh();
    });
  };

  if (initialDrafts.length === 0) {
    return <HomeEmptyState message="no drafts saved" buttonText="start a new trail" />;
  }

  return (
    <div className="drafts-pills">
      {initialDrafts.map((draft) => (
        <HomeWalkingPill
          key={draft.rkey}
          title={draft.title || "untitled draft"}
          subtitle={`${draft.stopsCount} ${draft.stopsCount === 1 ? "stop" : "stops"}`}
          accentColor={draft.accentColor}
          backgroundColor={draft.backgroundColor}
          linkTo={`/drafts/${draft.rkey}`}
          dots={Array(draft.stopsCount).fill("upcoming")}
          onDelete={() => handleDelete(draft.rkey)}
          deleteLabel="delete draft"
          deleteConfirmMessage="delete this draft?"
        />
      ))}
    </div>
  );
}
