"use client";
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { RefreshCw, CheckCircle2 } from "lucide-react";
import { clearCache } from "@/app/actions/maintenance";

export function ClearCacheButton() {
  const [done, setDone] = useState(false);
  const [pending, start] = useTransition();
  const router = useRouter();

  const onClick = () => {
    start(async () => {
      await clearCache();
      router.refresh();
      setDone(true);
      setTimeout(() => setDone(false), 1600);
    });
  };

  return (
    <div className="flex items-start justify-between gap-4 py-2">
      <div className="min-w-0">
        <div className="text-sm font-medium">Clear Cache</div>
        <div className="text-xs text-[var(--color-fg-muted)] mt-0.5">
          Drop the in-memory settings cache and force every page to re-fetch from the database.
          Useful if data looks stale after a manual edit.
        </div>
      </div>
      <div className="flex-shrink-0 flex items-center gap-2">
        {done ? (
          <span className="flex items-center gap-1.5 text-xs text-[var(--color-mint)]">
            <CheckCircle2 className="w-3.5 h-3.5" /> Cleared
          </span>
        ) : (
          <button
            onClick={onClick}
            disabled={pending}
            className="inline-flex items-center justify-center gap-1.5 min-w-[100px] text-xs px-3 py-1.5 rounded-lg glass glass-hover text-[var(--color-fg-dim)] hover:text-[var(--color-fg)] disabled:opacity-50 whitespace-nowrap"
          >
            <RefreshCw className={`w-3.5 h-3.5 ${pending ? "animate-spin" : ""}`} />
            {pending ? "Clearing…" : "Clear"}
          </button>
        )}
      </div>
    </div>
  );
}
