'use client'

import type * as React from 'react'
import type { FormSettingsRow } from './forms-settings-columns'
import type { ColumnDef } from '@tanstack/react-table'
import {
  DataGrid,
  DataGridBody,
  DataGridCell,
  DataGridHead,
  DataGridHeader,
  DataGridRow
} from '@admin/components/shared/data-table/data-grid'
import { cn } from '@admin/utils/shared/cn'
import { flexRender, getCoreRowModel, useReactTable } from '@tanstack/react-table'

interface FormsSettingsTableProps extends React.HTMLAttributes<HTMLDivElement> {
  columns: ColumnDef<FormSettingsRow>[]
  rows: FormSettingsRow[]
  onRowClick: (row: FormSettingsRow) => void
}

export function FormsSettingsTable({
  columns,
  rows,
  onRowClick,
  className
}: FormsSettingsTableProps) {
  const table = useReactTable({
    data: rows,
    columns,
    getCoreRowModel: getCoreRowModel()
  })

  return (
    <div className={cn('flex h-full flex-col gap-6 pt-px pb-2', className)}>
      <DataGrid
        containerClassName="min-h-0 flex-1"
        gridTemplateColumns="minmax(200px, 1fr) minmax(240px, 2fr)"
      >
        <DataGridHeader>
          {table.getHeaderGroups().map((headerGroup) => (
            <DataGridRow key={headerGroup.id}>
              {headerGroup.headers.map((header) => (
                <DataGridHead key={header.id} className="overflow-hidden">
                  {header.isPlaceholder
                    ? null
                    : flexRender(header.column.columnDef.header, header.getContext())}
                </DataGridHead>
              ))}
            </DataGridRow>
          ))}
        </DataGridHeader>
        <DataGridBody>
          {table.getRowModel().rows.length ? (
            table.getRowModel().rows.map((row) => (
              <DataGridRow
                key={row.id}
                className="cursor-pointer hover:bg-muted/50"
                onClick={(event) => {
                  const target = event.target as HTMLElement
                  if (!event.currentTarget.contains(target)) return
                  if (target.closest('button, a, input, [role="checkbox"]')) return
                  onRowClick(row.original)
                }}
              >
                {row.getVisibleCells().map((cell) => (
                  <DataGridCell key={cell.id} data-column-id={cell.column.id}>
                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                  </DataGridCell>
                ))}
              </DataGridRow>
            ))
          ) : (
            <DataGridRow>
              <DataGridCell
                className="flex h-24 items-center justify-center text-center text-muted-foreground"
                style={{ gridColumn: '1 / -1' }}
              >
                No forms yet. Create a form schema to configure its notifications here.
              </DataGridCell>
            </DataGridRow>
          )}
        </DataGridBody>
      </DataGrid>
    </div>
  )
}
