import { RefObject } from "react";
import { useNotesStore } from "../../store/notesStore";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faBars } from "@fortawesome/free-solid-svg-icons";
import Button from "../ui/Button";

const textColors = ["#1f2937", "#1d4ed8", "#b91c1c", "#15803d", "#7c3aed", "#c2410c"];
const highlightColors = ["#fef08a", "#bae6fd", "#fecaca", "#bbf7d0", "#e9d5ff", "#fed7aa"];

type ToolbarProps = {
  textareaRef: RefObject<HTMLTextAreaElement>;
};

export default function Toolbar({ textareaRef }: ToolbarProps) {
  const activeNote = useNotesStore((state) => state.activeNote);
  const updateActive = useNotesStore((state) => state.updateActive);

  if (!activeNote) {
    return null;
  }

  const applyWrap = (before: string, after = before) => {
    const textarea = textareaRef.current;
    if (!textarea) {
      return;
    }
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const value = activeNote.content;
    const selected = value.slice(start, end) || "metin";
    const nextValue = `${value.slice(0, start)}${before}${selected}${after}${value.slice(end)}`;
    updateActive(activeNote.title, nextValue);
    requestAnimationFrame(() => {
      textarea.focus();
      textarea.selectionStart = start + before.length;
      textarea.selectionEnd = start + before.length + selected.length;
    });
  };

  const applyLinePrefix = (prefix: string) => {
    const textarea = textareaRef.current;
    if (!textarea) {
      return;
    }
    const value = activeNote.content;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const before = value.slice(0, start);
    const selection = value.slice(start, end) || "Satir";
    const lines = selection.split("\n").map((line) => `${prefix}${line}`);
    const nextValue = `${before}${lines.join("\n")}${value.slice(end)}`;
    updateActive(activeNote.title, nextValue);
  };

  const applyColor = (hex: string) => applyWrap(`<span style=\"color:${hex}\">`, "</span>");
  const applyHighlight = (hex: string) => applyWrap(`<mark style=\"background:${hex}\">`, "</mark>");

  return (
    <div className="mt-4 flex flex-wrap items-center gap-2">
      <Button
        className="border border-slate-200 px-3 py-1 text-xs"
        onClick={() => applyWrap("**")}
      >
        Kalin
      </Button>
      <Button
        className="border border-slate-200 px-3 py-1 text-xs"
        onClick={() => applyWrap("~~")}
      >
        Ust
      </Button>
      <Button
        className="border border-slate-200 px-3 py-1 text-xs"
        onClick={() => applyLinePrefix("- ")}
        aria-label="Liste"
      >
        <FontAwesomeIcon icon={faBars} className="h-3.5 w-3.5" />
      </Button>
      <Button
        className="border border-slate-200 px-3 py-1 text-xs"
        onClick={() => applyLinePrefix("1. ")}
      >
        Numara
      </Button>
      <div className="flex items-center gap-1">
        {textColors.map((hex) => (
          <Button
            key={hex}
            className="h-6 w-6 border border-white shadow"
            style={{ background: hex }}
            onClick={() => applyColor(hex)}
            aria-label={`Renk ${hex}`}
          />
        ))}
      </div>
      <div className="flex items-center gap-1">
        {highlightColors.map((hex) => (
          <Button
            key={hex}
            className="h-6 w-6 border border-white shadow"
            style={{ background: hex }}
            onClick={() => applyHighlight(hex)}
            aria-label={`Vurgula ${hex}`}
          />
        ))}
      </div>
    </div>
  );
}
