"use client";

import { useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import { toast } from "sonner";
import { Download, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import { isRecipeSavedOffline, saveRecipeOffline, unsaveRecipeOffline } from "@/lib/offline-db";

export function SaveOfflineButton({ recipeId, recipeTitle }: { recipeId: string; recipeTitle: string }) {
  const pathname = usePathname();
  const [saved, setSaved] = useState(false);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    isRecipeSavedOffline(recipeId).then(setSaved).catch(() => {});
  }, [recipeId]);

  async function toggle() {
    setBusy(true);
    try {
      if (saved) {
        await unsaveRecipeOffline(recipeId);
        setSaved(false);
        toast.success("Removed from offline recipes");
        return;
      }
      // Re-fetching the current page (rather than relying on the visit that
      // already happened) forces the service worker's fetch handler to pin
      // a fresh copy in its cache right now, regardless of how the normal
      // cache eviction/versioning plays out later.
      await fetch(pathname, { cache: "reload" });
      await saveRecipeOffline(recipeId, recipeTitle);
      setSaved(true);
      toast.success("Saved for offline — photos and linked pages aren't included");
    } catch {
      toast.error("Couldn't save this recipe for offline use");
    } finally {
      setBusy(false);
    }
  }

  return (
    <Button type="button" variant="outline" size="sm" disabled={busy} onClick={() => { void toggle(); }}>
      {saved ? <Check className="h-3.5 w-3.5" /> : <Download className="h-3.5 w-3.5" />}
      {saved ? "Saved offline" : "Save offline"}
    </Button>
  );
}
