'use client';

import { useState, useTransition, useRef, useEffect, useMemo } from 'react';

interface EditableTitleProps {
  sessionId: string;
  initialTitle: string;
  canEdit: boolean;
  onUpdate: (sessionId: string, title: string) => Promise<{ success: boolean; error?: string }>;
}

export function EditableTitle({ sessionId, initialTitle, canEdit, onUpdate }: EditableTitleProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [editingTitle, setEditingTitle] = useState('');
  const [isPending, startTransition] = useTransition();
  const inputRef = useRef<HTMLInputElement>(null);

  // Use editingTitle when editing, otherwise use initialTitle (synced from SSE)
  const title = useMemo(
    () => (isEditing ? editingTitle : initialTitle),
    [isEditing, editingTitle, initialTitle]
  );

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

  const handleSave = () => {
    const trimmedTitle = editingTitle.trim();
    if (!trimmedTitle) {
      setEditingTitle('');
      setIsEditing(false);
      return;
    }

    if (trimmedTitle === initialTitle) {
      setEditingTitle('');
      setIsEditing(false);
      return;
    }

    startTransition(async () => {
      const result = await onUpdate(sessionId, trimmedTitle);
      if (!result.success) {
        setEditingTitle('');
        console.error(result.error);
      }
      setIsEditing(false);
      setEditingTitle('');
    });
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleSave();
    } else if (e.key === 'Escape') {
      setEditingTitle('');
      setIsEditing(false);
    }
  };

  if (!canEdit) {
    return <h1 className="text-3xl font-bold text-foreground">{title}</h1>;
  }

  if (isEditing) {
    return (
      <input
        ref={inputRef}
        type="text"
        value={editingTitle}
        onChange={(e) => setEditingTitle(e.target.value)}
        onBlur={handleSave}
        onKeyDown={handleKeyDown}
        disabled={isPending}
        className="w-full max-w-md rounded-lg border border-border bg-input px-3 py-1.5 text-3xl font-bold text-foreground outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 disabled:opacity-50"
      />
    );
  }

  return (
    <button
      onClick={() => {
        setEditingTitle(initialTitle);
        setIsEditing(true);
      }}
      className="group flex items-center gap-2 text-left"
      title="Cliquez pour modifier"
    >
      <h1 className="text-3xl font-bold text-foreground">{title}</h1>
      <svg
        className="h-5 w-5 text-muted opacity-0 transition-opacity group-hover:opacity-100"
        fill="none"
        viewBox="0 0 24 24"
        stroke="currentColor"
      >
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          strokeWidth={2}
          d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"
        />
      </svg>
    </button>
  );
}
