'use client'

import type { Editor } from '@tiptap/core'
import { Button } from '@admin/components/ui/button'
import { Input } from '@admin/components/ui/input'
import { Label } from '@admin/components/ui/label'
import { Popover, PopoverContent, PopoverTrigger } from '@admin/components/ui/popover'
import { useTableButton } from '@admin/hooks/content-editor/use-table-button'
import { TableIcon } from 'lucide-react'

interface TableButtonProps {
  disabled?: boolean
  editor?: Editor | null
  onInsertTable?: (size: { cols: number; rows: number }) => void
}

export function TableButton({ disabled, editor, onInsertTable }: TableButtonProps) {
  const tableButton = useTableButton({ disabled, editor, onInsertTable })

  return (
    <Popover open={tableButton.isOpen} onOpenChange={tableButton.setIsOpen}>
      <PopoverTrigger
        render={
          <Button
            type="button"
            variant="ghost"
            size="sm"
            disabled={tableButton.isDisabled}
            aria-label="Insert table"
            title="Table"
          />
        }
      >
        <TableIcon />
        <span className="tiptap-button-text">Table</span>
      </PopoverTrigger>
      <PopoverContent align="start" className="w-72 p-4">
        <div className="flex flex-col gap-3" onKeyDownCapture={tableButton.handleKeyDown}>
          <div className="grid grid-cols-2 gap-2">
            <div className="flex flex-col gap-1.5">
              <Label htmlFor={tableButton.rowsId}>Rows</Label>
              <Input
                id={tableButton.rowsId}
                inputMode="numeric"
                min={tableButton.minRows}
                onChange={tableButton.handleRowsChange}
                type="number"
                value={tableButton.rows}
              />
            </div>
            <div className="flex flex-col gap-1.5">
              <Label htmlFor={tableButton.colsId}>Cols</Label>
              <Input
                id={tableButton.colsId}
                inputMode="numeric"
                min={tableButton.minCols}
                onChange={tableButton.handleColsChange}
                type="number"
                value={tableButton.cols}
              />
            </div>
          </div>
          <Button
            type="button"
            variant="default"
            disabled={tableButton.isDisabled}
            onClick={tableButton.insertTable}
          >
            Insert
          </Button>
        </div>
      </PopoverContent>
    </Popover>
  )
}
