import React, { useEffect, useRef, useState } from 'react';
import { ArrowUp, Pencil, X } from 'lucide-react';
import useRenderTracker from '../../../hooks/useRenderTracker';
import MessageAttachments, { type MessageAttachment } from '../MessageAttachments';

interface UserMessageProps {
  content: string;
  messageId?: string;
  isLatestEditable?: boolean;
  onEditAndResubmit?: (messageId: string, text: string) => void;
  attachments?: MessageAttachment[];
}

const UserMessage = ({ content, messageId, isLatestEditable, onEditAndResubmit, attachments }: UserMessageProps) => {
  useRenderTracker('UserMessage', { content });
  const canEdit = Boolean(messageId) && Boolean(isLatestEditable);
  const [isEditing, setIsEditing] = useState(false);
  const [draft, setDraft] = useState(content);
  const editRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    if (isEditing) {
      setDraft(content);
      const el = editRef.current;
      if (el) {
        el.style.height = 'auto';
        el.style.height = `${el.scrollHeight}px`;
        el.focus();
        el.setSelectionRange(el.value.length, el.value.length);
      }
    }
  }, [isEditing, content]);

  const save = () => {
    const trimmed = draft.trim();
    if (trimmed && messageId) {
      onEditAndResubmit?.(messageId, trimmed);
    }
    setIsEditing(false);
  };

  if (isEditing) {
    return (
      <div className="flex justify-end">
        <div className="my-2 w-full max-w-[80%] rounded-2xl rounded-br-md border border-brand bg-app-surface p-2 shadow-sm ring-2 ring-brand/25">
          <textarea
            ref={editRef}
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                save();
              } else if (e.key === 'Escape') {
                setIsEditing(false);
              }
            }}
            rows={1}
            aria-label="Edit message"
            className="max-h-[200px] w-full resize-none bg-transparent px-2 py-1 text-sm text-app-text outline-none scrollbar-custom sm:text-[0.95rem]"
          />
          <div className="mt-1 flex justify-end gap-1.5">
            <button
              type="button"
              onClick={() => setIsEditing(false)}
              aria-label="Cancel edit"
              className="flex h-8 w-8 items-center justify-center rounded-md text-app-muted transition-colors hover:bg-app-surface-hover hover:text-app-text focus:outline-none focus-visible:ring-2 focus-visible:ring-brand"
            >
              <X size={16} />
            </button>
            <button
              type="button"
              onClick={save}
              aria-label="Save and resubmit"
              className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-button text-white shadow-sm transition-all hover:bg-brand-button-hover active:scale-95 focus:outline-none focus-visible:ring-2 focus-visible:ring-brand"
            >
              <ArrowUp size={18} strokeWidth={2.5} />
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="group/msg flex justify-end">
      <div className="relative flex max-w-[80%] flex-col items-end">
        <div className="my-1 inline-block max-w-full overflow-hidden rounded-2xl rounded-br-md border border-app-border bg-app-selected px-4 py-2.5 text-sm text-app-text sm:text-[0.95rem]">
          <MessageAttachments attachments={attachments} />
          <div className="max-w-none overflow-hidden whitespace-pre-wrap text-left">
            {content}
          </div>
        </div>
        {canEdit && (
          <button
            type="button"
            onClick={() => setIsEditing(true)}
            aria-label="Edit message"
            className="absolute right-0 top-full flex items-center gap-1 rounded-md px-1.5 py-0.5 text-xs font-medium text-app-muted opacity-0 transition-opacity hover:text-app-text focus:outline-none focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-brand group-hover/msg:opacity-100"
          >
            <Pencil size={13} />
            Edit
          </button>
        )}
      </div>
    </div>
  );
};

export default React.memo(UserMessage);
