"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Lock } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";

export function RecipeNotes({
  recipeId,
  initialContent,
}: {
  recipeId: string;
  initialContent: string;
}) {
  const t = useTranslations("recipeNotes");
  const [content, setContent] = useState(initialContent);
  const [savedContent, setSavedContent] = useState(initialContent);
  const [saving, setSaving] = useState(false);

  const dirty = content !== savedContent;

  async function save() {
    setSaving(true);
    try {
      const res = await fetch(`/api/v1/recipes/${recipeId}/notes`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ content }),
      });
      if (!res.ok) {
        toast.error(t("saveFailed"));
        return;
      }
      const data = (await res.json()) as { note: { content: string } | null };
      const newContent = data.note?.content ?? "";
      setContent(newContent);
      setSavedContent(newContent);
      toast.success(t("saved"));
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="rounded-lg border border-dashed p-4 space-y-3">
      <div className="flex items-center gap-2 text-sm font-medium">
        <Lock className="h-4 w-4 text-muted-foreground" />
        {t("title")}
      </div>
      <p className="text-xs text-muted-foreground">{t("visibilityHint")}</p>
      <Textarea
        value={content}
        onChange={(e) => setContent(e.target.value)}
        onBlur={() => dirty && !saving && save()}
        placeholder={t("placeholder")}
        maxLength={5000}
        rows={3}
      />
      <div className="flex justify-end">
        <Button type="button" size="sm" variant="outline" disabled={!dirty || saving} onClick={save}>
          {saving ? t("saving") : t("save")}
        </Button>
      </div>
    </div>
  );
}
