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

/**
 * AutoSaveTextarea is a textarea that auto-saves its value after the user stops typing for a short delay.
 * Shows a green flash and a "saved" message when the save is successful.
 */
export function AutoSaveTextarea({
  value: initialValue,
  onSave,
  delay = 500,
  className = "",
  multiline = true,
  ...props
}: {
  value: string;
  onSave: (value: string) => Promise<void>;
  delay?: number;
  className?: string;
  multiline?: boolean;
  [key: string]: any;
}) {
  const [value, setValue] = useState(initialValue || "");
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [flash, setFlash] = useState(false);
  const timeoutRef = useRef<number | null>(null);
  const saveTimeoutRef = useRef<number | null>(null);

  useEffect(() => {
    setValue(initialValue || "");
  }, [initialValue]);

  useEffect(() => {
    return () => {
      if (timeoutRef.current) window.clearTimeout(timeoutRef.current);
      if (saveTimeoutRef.current) window.clearTimeout(saveTimeoutRef.current);
    };
  }, []);

  const handleChange = (
    e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>,
  ) => {
    setValue(e.target.value);
    setSaved(false);
    setFlash(false);
    if (timeoutRef.current) window.clearTimeout(timeoutRef.current);
    timeoutRef.current = window.setTimeout(async () => {
      setSaving(true);
      try {
        await onSave(e.target.value);
        setSaved(true);
        setFlash(true);
        saveTimeoutRef.current = window.setTimeout(() => setFlash(false), 600);
      } finally {
        setSaving(false);
      }
    }, delay);
  };

  return (
    <div className="relative">
      {multiline ? (
        <textarea
          value={value}
          onChange={handleChange}
          className={`w-full min-h-[4rem] p-2 rounded border bg-slate-800 text-slate-100 border-slate-700 focus:outline-none focus:ring-2 focus:ring-violet-500 transition-colors ${flash ? "ring-2 ring-emerald-400 border-emerald-400 bg-emerald-950" : ""} ${className}`}
          {...props}
        />
      ) : (
        <input
          value={value}
          onChange={handleChange}
          className={`w-full p-2 rounded border bg-slate-800 text-slate-100 border-slate-700 focus:outline-none focus:ring-2 focus:ring-violet-500 transition-colors ${flash ? "ring-2 ring-emerald-400 border-emerald-400 bg-emerald-950" : ""} ${className}`}
          {...props}
        />
      )}
      {saved && !saving && (
        <span className="absolute bottom-1 right-2 text-emerald-400 text-xs bg-slate-900 bg-opacity-80 px-2 py-0.5 rounded shadow">
          Saved
        </span>
      )}
    </div>
  );
}
