"use client";

import { useEffect, useRef, useState } from "react";

type OrderNoteTextareaProps = {
  initialValue: string;
  title: string;
  description: string;
  placeholder: string;
  savingLabel: string;
  savedLabel: string;
  errorLabel: string;
};

export function OrderNoteTextarea({
  initialValue,
  title,
  description,
  placeholder,
  savingLabel,
  savedLabel,
  errorLabel,
}: OrderNoteTextareaProps) {
  const [value, setValue] = useState(initialValue);
  const [status, setStatus] = useState<"idle" | "saving" | "saved" | "error">("idle");
  const lastSavedValueRef = useRef(initialValue);
  const firstRenderRef = useRef(true);

  useEffect(() => {
    setValue(initialValue);
    lastSavedValueRef.current = initialValue;
  }, [initialValue]);

  useEffect(() => {
    if (firstRenderRef.current) {
      firstRenderRef.current = false;
      return;
    }

    if (value === lastSavedValueRef.current) {
      return;
    }

    const timeout = window.setTimeout(async () => {
      setStatus("saving");

      try {
        const response = await fetch("/api/cart/order-note", {
          method: "POST",
          headers: {
            "content-type": "application/json",
          },
          body: JSON.stringify({ note: value }),
        });

        if (!response.ok) {
          throw new Error("save-failed");
        }

        lastSavedValueRef.current = value;
        setStatus("saved");
        window.setTimeout(() => setStatus("idle"), 1600);
      } catch {
        setStatus("error");
      }
    }, 700);

    return () => window.clearTimeout(timeout);
  }, [value]);

  return (
    <div className="space-y-3 rounded-2xl border border-[var(--line)] bg-[#fffafa] p-4">
      <div className="space-y-1">
        <p className="text-sm font-medium text-[var(--foreground)]">{title}</p>
        <p className="text-sm text-[var(--muted)]">{description}</p>
      </div>
      <textarea
        name="orderNote"
        value={value}
        onChange={(event) => setValue(event.target.value)}
        placeholder={placeholder}
        rows={5}
        maxLength={1000}
        className="min-h-[132px] w-full resize-y rounded-2xl border border-[var(--line)] bg-white px-4 py-3 text-sm text-[var(--foreground)] outline-none transition focus:border-[#f5505080] focus:shadow-[0_0_0_4px_rgba(245,80,80,0.08)]"
      />
      <div className="flex items-center justify-between gap-3 text-xs">
        <span className="text-[var(--muted)]">{value.length}/1000</span>
        <span
          className={
            status === "error"
              ? "text-[#a21717]"
              : status === "saved"
                ? "text-[#0e5c45]"
                : "text-[var(--muted)]"
          }
        >
          {status === "saving" ? savingLabel : status === "saved" ? savedLabel : status === "error" ? errorLabel : ""}
        </span>
      </div>
    </div>
  );
}
