"use client";

import { useState, useRef, useCallback, useEffect } from "react";
import { StickyNote } from "lucide-react";

export function InlineNotes({ value, onSave }: { value: string; onSave: (notes: string) => void }) {
  const [editing, setEditing] = useState(false);
  const [text, setText] = useState(value);
  const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => { setText(value); }, [value]);

  const save = useCallback((v: string) => {
    clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => onSave(v), 800);
  }, [onSave]);

  function handleChange(v: string) {
    setText(v);
    save(v);
  }

  useEffect(() => {
    if (editing && textareaRef.current) {
      textareaRef.current.focus();
      textareaRef.current.selectionStart = textareaRef.current.value.length;
    }
  }, [editing]);

  if (!editing && !value) {
    return (
      <button
        onClick={() => setEditing(true)}
        className="mt-2 inline-flex items-center gap-1.5 text-[11px] text-neutral-600 hover:text-neutral-400 transition-colors"
      >
        <StickyNote size={11} />
        Добавить заметку...
      </button>
    );
  }

  if (!editing) {
    return (
      <button
        onClick={() => setEditing(true)}
        className="mt-2 flex items-start gap-1.5 rounded-md bg-amber-500/[0.06] border border-amber-500/10 px-2.5 py-1.5 text-left transition-colors hover:bg-amber-500/10"
      >
        <StickyNote size={11} className="shrink-0 mt-0.5 text-amber-500/60" />
        <span className="text-[11px] text-amber-200/70 leading-relaxed whitespace-pre-wrap">{value}</span>
      </button>
    );
  }

  return (
    <div className="mt-2">
      <textarea
        ref={textareaRef}
        value={text}
        onChange={(e) => handleChange(e.target.value)}
        onBlur={() => { clearTimeout(timerRef.current); if (text !== value) onSave(text.trim() ? text : ""); setEditing(false); }}
        placeholder="Заметка..."
        rows={2}
        className="w-full rounded-md border border-amber-500/20 bg-amber-500/[0.06] px-2.5 py-1.5 text-[11px] text-amber-200/80 placeholder-neutral-600 outline-none focus:border-amber-500/40 resize-none"
      />
    </div>
  );
}
