"use client";

import { useEffect, useState, useTransition } from "react";
import { pushOverdueToTaskList } from "../server/actions";

export function PushOverdueButton() {
  const [message, setMessage] = useState<string | null>(null);
  const [isError, setIsError] = useState(false);
  const [isPending, startTransition] = useTransition();

  useEffect(() => {
    if (!message) return;
    const id = setTimeout(() => setMessage(null), 4000);
    return () => clearTimeout(id);
  }, [message]);

  function handleClick() {
    setMessage(null);
    setIsError(false);
    startTransition(async () => {
      try {
        const { added } = await pushOverdueToTaskList();
        setMessage(
          added === 0
            ? "No overdue care tasks."
            : `Added ${added} task${added !== 1 ? "s" : ""} to your task list.`,
        );
      } catch {
        setIsError(true);
        setMessage("Failed to push tasks. Please try again.");
      }
    });
  }

  return (
    <div className="flex items-center gap-2">
      <button onClick={handleClick} disabled={isPending} className="btn btn-ghost btn-sm">
        {isPending ? "Pushing…" : "Add overdue to task list"}
      </button>
      {message && (
        <span className={`text-xs ${isError ? "text-red-500" : "text-[var(--ink-mute)]"}`}>
          {message}
        </span>
      )}
    </div>
  );
}
