"use client";

import { Copy, Plus } from "lucide-react";
import { v4 as uuidv4 } from "uuid";
import { IBlock, INote } from "@/lib/db/schema";
import { createBlock } from "@/app/actions/blocks";
import IconOnlyButton from "../ui/IconOnlyButton";
import Block from "./Block";

const defaultNoteId = uuidv4();

const defaultNote: INote = {
  id: defaultNoteId,
  title: "Untitled",
  creationTime: new Date(),
  lastEdited: new Date(),
  authorId: uuidv4(),
};

const defaultBlocks: IBlock[] = [
  {
    id: uuidv4(),
    tag: "",
    lines: ["", "", "", ""],
    isLocked: false,
    order: 1,
    noteId: defaultNoteId,
  },
];

export default function Editor({
  note = defaultNote,
  blocks = defaultBlocks,
}: {
  note?: INote;
  blocks?: IBlock[];
}) {
  const copyHandler = () => {
    let copyText = "";
    blocks.forEach((block) => {
      if (block.tag !== "") {
        copyText += `[${block.tag}]`;
      }
      copyText += block.lines.join("\n");
    });
    navigator.clipboard.writeText(copyText);
  }

  return (
    <div className="flex flex-col items-center max-w-2xl w-full gap-4">
      <input
        className="font-bold text-xl w-full text-center focus:outline-none"
        defaultValue={note.title}
      />
      {blocks.map((block) => <Block key={block.id} block={block} /> )}
      <div className="flex gap-2">
        <form action={createBlock}>
          <input type="hidden" name="noteId" value={note.id} />
          <IconOnlyButton icon={<Plus size={24} />} type="submit" />
        </form>
        <IconOnlyButton icon={<Copy size={24} />} onClick={copyHandler} title="Copy note to clipboard" />
      </div>
    </div>
  );
}
