'use client'

/**
 * Shared, token-only submissions table used by both the per-form Submissions
 * view and the global All Entries inbox. Presentational only: selection, star,
 * and row-open are delegated to the parent; an optional Form column links each
 * row back to its form when entries span multiple forms.
 */
import type { ReactNode } from 'react'
import { Star } from 'lucide-react'
import type { FormSubmission } from '../../lib/forms-service.js'
import { btnGhostIcon } from './primitives.js'

export function formatEntryDateTime(iso: string | null | undefined): string {
  if (!iso) return '—'
  const d = new Date(iso)
  if (Number.isNaN(d.getTime())) return '—'
  return d.toLocaleString(undefined, {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  })
}

export interface EntriesTableProps {
  entries: FormSubmission[]
  selected: Set<string>
  allSelected: boolean
  onToggleSelectAll: () => void
  onToggleSelect: (id: string) => void
  onOpen: (id: string) => void
  onToggleStar: (entry: FormSubmission) => void
  /** Show a Form column (used by the cross-form All Entries inbox). */
  showForm?: boolean
  /** Navigate to a form's submissions when its name is clicked (All Entries). */
  onOpenForm?: (formId: string) => void
  /** Accessible label for the table element. */
  ariaLabel?: string
  /** Footer row (e.g. pagination) rendered inside the bordered card. */
  footer?: ReactNode
}

export function EntriesTable({
  entries,
  selected,
  allSelected,
  onToggleSelectAll,
  onToggleSelect,
  onOpen,
  onToggleStar,
  showForm = false,
  onOpenForm,
  ariaLabel = 'Submissions',
  footer,
}: EntriesTableProps) {
  return (
    <div className="border-border bg-card rounded-lg border">
      <div className="overflow-x-auto">
        <table
          className={`w-full ${showForm ? 'min-w-[860px]' : 'min-w-[720px]'} text-sm`}
          aria-label={ariaLabel}
        >
          <thead>
            <tr className="border-border text-muted-foreground border-b text-left text-xs">
              <th scope="col" className="w-10 px-4 py-2.5">
                <input
                  type="checkbox"
                  checked={allSelected}
                  onChange={onToggleSelectAll}
                  aria-label="Select all submissions"
                  className="border-border text-primary focus-visible:ring-ring h-4 w-4 rounded"
                />
              </th>
              <th scope="col" className="px-4 py-2.5 font-medium">
                Sender
              </th>
              {showForm && (
                <th scope="col" className="px-4 py-2.5 font-medium whitespace-nowrap">
                  Form
                </th>
              )}
              <th scope="col" className="px-4 py-2.5 font-medium">
                Submission
              </th>
              <th scope="col" className="px-4 py-2.5 font-medium whitespace-nowrap">
                Submitted
              </th>
              <th scope="col" className="w-10 px-4 py-2.5 text-center font-medium">
                <span className="sr-only">Starred</span>
              </th>
            </tr>
          </thead>
          <tbody>
            {entries.map((entry) => {
              const isSelected = selected.has(entry.id)
              const name = entry.senderName || 'Anonymous'
              return (
                <tr
                  key={entry.id}
                  className={`border-border hover:bg-accent/40 group cursor-pointer border-b transition-colors last:border-b-0 ${
                    isSelected ? 'bg-accent/30' : ''
                  }`}
                  onClick={() => onOpen(entry.id)}
                >
                  <td className="px-4 py-3" onClick={(e) => e.stopPropagation()}>
                    <input
                      type="checkbox"
                      checked={isSelected}
                      onChange={() => onToggleSelect(entry.id)}
                      aria-label={`Select submission from ${name}`}
                      className="border-border text-primary focus-visible:ring-ring h-4 w-4 rounded"
                    />
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-3">
                      <span
                        className="bg-muted text-muted-foreground flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-medium"
                        aria-hidden
                      >
                        {name.charAt(0).toUpperCase()}
                      </span>
                      <div className="min-w-0">
                        <div className="flex items-center gap-2">
                          {entry.unread && (
                            <span
                              className="bg-primary h-1.5 w-1.5 shrink-0 rounded-full"
                              aria-label="Unread"
                            />
                          )}
                          <span
                            className={`text-foreground truncate ${entry.unread ? 'font-semibold' : 'font-medium'}`}
                          >
                            {name}
                          </span>
                        </div>
                        {entry.senderEmail && (
                          <span className="text-muted-foreground block truncate text-xs">
                            {entry.senderEmail}
                          </span>
                        )}
                      </div>
                    </div>
                  </td>
                  {showForm && (
                    <td
                      className="px-4 py-3 whitespace-nowrap"
                      onClick={(e) => e.stopPropagation()}
                    >
                      {onOpenForm ? (
                        <button
                          type="button"
                          onClick={() => onOpenForm(entry.formId)}
                          className="text-muted-foreground hover:text-primary focus-visible:ring-ring rounded text-sm focus-visible:ring-2 focus-visible:outline-none"
                        >
                          {entry.formName || '—'}
                        </button>
                      ) : (
                        <span className="text-muted-foreground text-sm">
                          {entry.formName || '—'}
                        </span>
                      )}
                    </td>
                  )}
                  <td className="px-4 py-3">
                    <span className="text-muted-foreground line-clamp-1 max-w-md">
                      {entry.preview || '—'}
                    </span>
                  </td>
                  <td className="text-muted-foreground px-4 py-3 whitespace-nowrap">
                    {formatEntryDateTime(entry.submittedAt)}
                  </td>
                  <td className="px-4 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                    <button
                      type="button"
                      className={btnGhostIcon}
                      aria-pressed={entry.starred}
                      aria-label={entry.starred ? 'Unstar submission' : 'Star submission'}
                      onClick={() => onToggleStar(entry)}
                    >
                      <Star
                        className={`h-4 w-4 ${entry.starred ? 'fill-warning text-warning' : ''}`}
                        aria-hidden
                      />
                    </button>
                  </td>
                </tr>
              )
            })}
          </tbody>
        </table>
      </div>
      {footer}
    </div>
  )
}
