'use client'

import * as React from 'react'
import type { FormSettingsRow } from './forms-settings-columns'
import { PageHeader } from '@admin/components/shared/page-header'
import { webhookEventSources } from '@admin/data/webhook-events'
import { useFormSettingsList } from '@admin/hooks/use-webhooks'
import { FormNotificationsDrawer } from './form-notifications-drawer'
import { createFormSettingsColumns } from './forms-settings-columns'
import { FormsSettingsTable } from './forms-settings-table'

export function FormsSettingsPageContent() {
  const { data: settings, isPending } = useFormSettingsList()
  const [selectedKey, setSelectedKey] = React.useState<string | null>(null)

  const rows = React.useMemo<FormSettingsRow[]>(
    () =>
      webhookEventSources.flatMap((source) => {
        if (source.kind !== 'form' || !source.settingsKey) return []

        return [
          {
            settingsKey: source.settingsKey,
            label: source.label,
            notificationEmails:
              settings?.find((entry) => entry.formName === source.settingsKey)
                ?.notificationEmails ?? null
          }
        ]
      }),
    [settings]
  )

  const columns = React.useMemo(() => createFormSettingsColumns(isPending), [isPending])
  const selectedRow = rows.find((row) => row.settingsKey === selectedKey) ?? null

  return (
    <React.Fragment>
      <PageHeader title="Form Settings" />
      <main className="flex-1 space-y-4 px-4 pt-4 pb-4">
        <FormsSettingsTable
          columns={columns}
          rows={rows}
          onRowClick={(row) => setSelectedKey(row.settingsKey)}
        />
      </main>
      {selectedRow ? (
        <FormNotificationsDrawer
          key={selectedRow.settingsKey}
          formLabel={selectedRow.label}
          settingsKey={selectedRow.settingsKey}
          initialEmails={selectedRow.notificationEmails ?? ''}
          open={selectedKey !== null}
          onOpenChange={(nextOpen) => {
            if (!nextOpen) setSelectedKey(null)
          }}
        />
      ) : null}
    </React.Fragment>
  )
}
