'use client';

import { useEffect, useRef, useState } from 'react';
import { Loader2, Pencil } from 'lucide-react';
import { cn } from '@/lib/utils';

interface InlineEditableTitleProps {
  value: string;
  onSave: (nextValue: string) => Promise<void> | void;
  className?: string;
  inputClassName?: string;
  disabled?: boolean;
}

export function InlineEditableTitle({
  value,
  onSave,
  className,
  inputClassName,
  disabled = false
}: InlineEditableTitleProps) {
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(value);
  const [saving, setSaving] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (!editing) setDraft(value);
  }, [editing, value]);

  useEffect(() => {
    if (editing) {
      inputRef.current?.focus();
      inputRef.current?.select();
    }
  }, [editing]);

  async function commit() {
    const trimmed = draft.trim();
    if (!trimmed || trimmed === value) {
      setDraft(value);
      setEditing(false);
      return;
    }
    setSaving(true);
    try {
      await onSave(trimmed);
      setEditing(false);
    } finally {
      setSaving(false);
    }
  }

  if (editing) {
    return (
      <div className={cn('relative min-w-0', className)}>
        <input
          ref={inputRef}
          value={draft}
          disabled={saving}
          onChange={(event) => setDraft(event.target.value)}
          onBlur={() => void commit()}
          onKeyDown={(event) => {
            if (event.key === 'Enter') {
              event.preventDefault();
              void commit();
            }
            if (event.key === 'Escape') {
              setDraft(value);
              setEditing(false);
            }
          }}
          className={cn(
            'w-full border-0 bg-transparent p-0 text-base font-semibold leading-tight text-[#1f2430] outline-none ring-0',
            inputClassName
          )}
        />
        {saving ? <Loader2 className="absolute -right-5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 animate-spin text-[#667085]" /> : null}
      </div>
    );
  }

  return (
    <div className={cn('group/title flex min-w-0 items-center gap-1.5', className)}>
      <button
        type="button"
        disabled={disabled}
        onClick={() => !disabled && setEditing(true)}
        className="min-w-0 truncate text-left text-base font-semibold leading-tight text-[#1f2430] transition hover:text-[#3390ec] disabled:cursor-default disabled:hover:text-[#1f2430]"
      >
        {value}
      </button>
      {!disabled ? (
        <button
          type="button"
          aria-label="Изменить название"
          onClick={() => setEditing(true)}
          className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-[#667085] opacity-0 transition hover:bg-[#f4f5f8] hover:text-[#3390ec] group-hover/title:opacity-100"
        >
          <Pencil className="h-3.5 w-3.5" />
        </button>
      ) : null}
    </div>
  );
}
