"use client";

import { useState, useRef, useEffect } from "react";
import { useEditMode } from "./EditModeProvider";
import { PencilIcon } from "@heroicons/react/24/outline";

type Props = {
  value: string;
  onChange: (val: string) => void;
  multiline?: boolean;
  markdown?: boolean;
  className?: string;
};

function renderBold(text: string): React.ReactNode {
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  return parts.map((part, i) =>
    part.startsWith("**") && part.endsWith("**")
      ? <strong key={i}>{part.slice(2, -2)}</strong>
      : part
  );
}

export function EditableText({ value, onChange, multiline = false, markdown = false, className = "" }: Props) {
  const { editMode } = useEditMode();
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(value);
  const inputRef = useRef<HTMLTextAreaElement | HTMLInputElement>(null);

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

  useEffect(() => {
    if (editing && inputRef.current) {
      inputRef.current.focus();
      const len = (inputRef.current as HTMLInputElement).value.length;
      (inputRef.current as HTMLInputElement).setSelectionRange(len, len);
    }
  }, [editing]);

  if (!editMode) {
    return <span className={className}>{markdown ? renderBold(value) : value}</span>;
  }

  if (editing) {
    const sharedProps = {
      ref: inputRef as React.RefObject<HTMLTextAreaElement & HTMLInputElement>,
      value: draft,
      onChange: (e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) =>
        setDraft(e.target.value),
      onBlur: () => {
        setEditing(false);
        if (draft !== value) onChange(draft);
      },
      onKeyDown: (e: React.KeyboardEvent) => {
        if (e.key === "Escape") {
          setDraft(value);
          setEditing(false);
        }
        if (!multiline && e.key === "Enter") {
          e.preventDefault();
          (e.target as HTMLElement).blur();
        }
      },
      onClick: (e: React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); },
      className:
        "w-full border border-sky-400 rounded px-1.5 py-0.5 text-inherit bg-sky-50 outline-none focus:ring-2 focus:ring-sky-400 resize-y " +
        className,
    };

    return multiline ? (
      <textarea {...sharedProps} rows={Math.max(2, draft.split("\n").length)} />
    ) : (
      <input {...sharedProps} type="text" />
    );
  }

  return (
    <span
      className={
        "cursor-pointer rounded px-0.5 hover:bg-sky-100 hover:outline hover:outline-1 hover:outline-sky-300 transition-colors group relative " +
        className
      }
      onClick={(e) => { e.preventDefault(); e.stopPropagation(); setEditing(true); }}
      title="Klikni za izmjenu"
    >
      {value}
      <PencilIcon className="inline ml-1 w-3 h-3 opacity-0 group-hover:opacity-60 text-sky-500" />
    </span>
  );
}
