import type { Editor } from "@tiptap/react"
import type {
  DocsTableBorder,
  DocsTableCellVerticalAlign,
} from "@/lib/drive/docs-table-types"

export function docsDefaultTableBorder(color = "#000000"): DocsTableBorder {
  return { size: 8, style: "single", color }
}

export function docsTableActive(editor: Editor | null): boolean {
  if (!editor) return false
  return editor.isActive("table")
}

export function docsTableCanMerge(editor: Editor | null): boolean {
  if (!editor) return false
  return editor.can().mergeCells()
}

export function docsTableCanSplit(editor: Editor | null): boolean {
  if (!editor) return false
  return editor.can().splitCell()
}

export function docsSetTableCellBackground(editor: Editor | null, color: string | null) {
  editor?.chain().focus().setCellAttribute("backgroundColor", color || null).run()
}

export function docsSetTableCellVerticalAlign(
  editor: Editor | null,
  verticalAlign: DocsTableCellVerticalAlign | null
) {
  editor?.chain().focus().setCellAttribute("verticalAlign", verticalAlign).run()
}

export function docsSetTableCellBorder(
  editor: Editor | null,
  side: "borderTop" | "borderRight" | "borderBottom" | "borderLeft",
  border: DocsTableBorder | string | null
) {
  editor?.chain().focus().setCellAttribute(side, border).run()
}

export function docsSetTableCellBordersAll(
  editor: Editor | null,
  border: DocsTableBorder | string | null
) {
  if (!editor) return
  editor
    .chain()
    .focus()
    .setCellAttribute("borderTop", border)
    .setCellAttribute("borderRight", border)
    .setCellAttribute("borderBottom", border)
    .setCellAttribute("borderLeft", border)
    .run()
}

export function docsClearTableCellBorders(editor: Editor | null) {
  docsSetTableCellBordersAll(editor, null)
}

export function docsSetTableRowHeight(editor: Editor | null, rowHeight: string | null) {
  if (!editor || !editor.isActive("table")) return
  editor.chain().focus().updateAttributes("tableRow", { rowHeight }).run()
}

export function docsSetTableAlignment(
  editor: Editor | null,
  alignment: "left" | "center" | "right" | null
) {
  if (!editor || !editor.isActive("table")) return
  editor.chain().focus().updateAttributes("table", { alignment }).run()
}

export function docsDistributeTableColumns(editor: Editor | null) {
  if (!editor || !editor.isActive("table")) return
  const table = editor.getAttributes("table")
  if (!table) return
  editor.commands.fixTables()
}
