"use client";

import { createReactBlockSpec } from "@blocknote/react";

const TODO_STATES = ["todo", "doing", "done", "cancelled"] as const;

const STATUS_LABELS: Record<(typeof TODO_STATES)[number], string> = {
  todo: "未开始",
  doing: "进行中",
  done: "已完成",
  cancelled: "已取消",
};

export const advancedTodoBlock = createReactBlockSpec(
  {
    type: "advancedTodo",
    propSchema: {
      status: {
        default: "todo",
        values: TODO_STATES,
      },
    },
    content: "inline",
  },
  {
    render: ({ block, editor }) => {
      const updateStatus = (next: (typeof TODO_STATES)[number]) => {
        editor.updateBlock(block, { props: { status: next } });
      };

      const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
        const current = block.props.status as (typeof TODO_STATES)[number];
        if (event.altKey) {
          updateStatus("cancelled");
          return;
        }
        const index = TODO_STATES.indexOf(current);
        const nextState = TODO_STATES[(index + 1) % TODO_STATES.length];
        updateStatus(nextState);
      };

      return (
        <div className="wolai-advanced-todo">
          <button
            type="button"
            className={`wolai-advanced-todo__status status-${block.props.status}`}
            onClick={handleClick}
          >
            {STATUS_LABELS[block.props.status as (typeof TODO_STATES)[number]]}
          </button>
          <div className="wolai-advanced-todo__content" />
        </div>
      );
    },
  },
)();
