"use client"

import { useState } from "react"
import { cn } from "@/lib/utils"

const MAX_ROWS = 8
const MAX_COLS = 10

export function DocsInsertTablePicker({
  onInsert,
}: {
  onInsert: (rows: number, cols: number) => void
}) {
  const [hover, setHover] = useState({ rows: 0, cols: 0 })

  const label =
    hover.rows > 0 && hover.cols > 0 ? `${hover.cols} x ${hover.rows}` : "Insérer un tableau"

  return (
    <div
      className="px-3 py-2"
      onMouseLeave={() => setHover({ rows: 0, cols: 0 })}
    >
      <div
        className="inline-grid gap-0.5"
        style={{ gridTemplateColumns: `repeat(${MAX_COLS}, 1fr)` }}
        role="grid"
        aria-label="Sélecteur de tableau"
      >
        {Array.from({ length: MAX_ROWS }, (_, rowIndex) =>
          Array.from({ length: MAX_COLS }, (_, colIndex) => {
            const row = rowIndex + 1
            const col = colIndex + 1
            const active = row <= hover.rows && col <= hover.cols
            return (
              <button
                key={`${row}-${col}`}
                type="button"
                className={cn(
                  "size-4 rounded-sm border border-[#dadce0] bg-white transition-colors",
                  "hover:border-[#1a73e8]",
                  active && "border-[#1a73e8] bg-[#d2e3fc]"
                )}
                aria-label={`${col} colonnes par ${row} lignes`}
                onMouseEnter={() => setHover({ rows: row, cols: col })}
                onClick={() => onInsert(row, col)}
              />
            )
          })
        )}
      </div>
      <p className="mt-2 text-center text-xs text-[#5f6368] dark:text-muted-foreground">
        {label}
      </p>
    </div>
  )
}
