import { useState } from 'react'
import { Table } from '@platform-modules/ui-primitives'
import { useSubmissions } from './useSubmissions.js'
import type { SubmissionClient } from './seams.js'

export interface SubmissionsTableProps {
  client: SubmissionClient
  formId: string
  /**
   * Render a stored `createdAt` ISO string for display. The host owns date
   * presentation (locale, ordering) — a CMS bound to a day-month-year
   * convention passes its own `Intl.DateTimeFormat` here. Defaults to the
   * runtime locale via `toLocaleString` (never a raw ISO string).
   */
  formatDate?: (iso: string) => string
}

function defaultFormatDate(iso: string): string {
  try {
    return new Date(iso).toLocaleString()
  } catch {
    return iso
  }
}

function previewData(data: Record<string, unknown>): string {
  const email = data.email
  if (typeof email === 'string' && email) return email
  const first = Object.values(data).find((v) => typeof v === 'string' && v)
  return typeof first === 'string' ? first : '—'
}

export function SubmissionsTable({ client, formId, formatDate = defaultFormatDate }: SubmissionsTableProps) {
  const [includeSpam, setIncludeSpam] = useState(false)
  const { items, loading, error, hasMore, loadMore, remove } = useSubmissions(client, formId, { includeSpam })

  return (
    <div>
      <label className="flex items-center gap-2 mb-4 text-sm">
        <input
          type="checkbox"
          checked={includeSpam}
          onChange={(e) => setIncludeSpam(e.target.checked)}
          aria-label="Show spam"
        />
        Show spam
      </label>

      {error ? (
        <div role="alert" className="text-sm text-danger mb-2">
          {error.message}
        </div>
      ) : null}

      {loading && items.length === 0 ? <p>Loading…</p> : null}

      <Table caption="Form submissions">
        <Table.Head>
          <Table.Row>
            <Table.Th scope="col">Created</Table.Th>
            <Table.Th scope="col">Data</Table.Th>
            <Table.Th scope="col">Status</Table.Th>
            <Table.Th scope="col">Actions</Table.Th>
          </Table.Row>
        </Table.Head>
        <Table.Body>
          {items.map((row) => (
            <Table.Row key={row.id}>
              <Table.Td>{formatDate(row.createdAt)}</Table.Td>
              <Table.Td>{previewData(row.data)}</Table.Td>
              <Table.Td>{row.spam ? <span>Spam</span> : <span>OK</span>}</Table.Td>
              <Table.Td>
                <button type="button" onClick={() => void remove(row.id)}>
                  Delete
                </button>
              </Table.Td>
            </Table.Row>
          ))}
        </Table.Body>
      </Table>

      {hasMore ? (
        <button type="button" onClick={() => void loadMore()} className="mt-4">
          Load more
        </button>
      ) : null}
    </div>
  )
}
