'use client'

import * as React from 'react'
import type { WebhookEndpointListItem } from '@admin/actions/webhooks'
import { EntityFiltersBar } from '@admin/components/shared/entity-filters-bar'
import { PageHeader } from '@admin/components/shared/page-header'
import { Button } from '@admin/components/ui/button'
import { useIsFetching } from '@tanstack/react-query'
import { Plus } from 'lucide-react'
import { parseAsInteger, parseAsString, useQueryState, useQueryStates } from 'nuqs'
import { DeleteWebhookDialog } from './delete-webhook-dialog'
import { WebhookEndpointDialog } from './webhook-endpoint-dialog'
import { createWebhooksColumns } from './webhooks-columns'
import { WebhooksTable } from './webhooks-table'

const filterParsers = {
  enabled: parseAsString.withDefault(''),
  lastDelivery: parseAsString.withDefault(''),
  createdAtFrom: parseAsString.withDefault(''),
  createdAtTo: parseAsString.withDefault('')
} as const

export function WebhooksPageContent() {
  const isSearchFetching = useIsFetching({ queryKey: ['webhooks'] }) > 0
  const [search, setSearch] = useQueryState('q', parseAsString.withDefault(''))
  const [, setPageIndex] = useQueryState('page', parseAsInteger.withDefault(0))

  const [filterValues, setFilters] = useQueryStates(filterParsers)
  const enabled = filterValues.enabled
  const lastDelivery = filterValues.lastDelivery
  const createdAtFrom = filterValues.createdAtFrom
  const createdAtTo = filterValues.createdAtTo

  const [dialogOpen, setDialogOpen] = React.useState(false)
  const [editingWebhook, setEditingWebhook] = React.useState<WebhookEndpointListItem | null>(null)
  const [deletingWebhook, setDeletingWebhook] = React.useState<WebhookEndpointListItem | null>(null)

  function openCreateDialog() {
    setEditingWebhook(null)
    setDialogOpen(true)
  }

  function openEditDialog(webhook: WebhookEndpointListItem) {
    setEditingWebhook(webhook)
    setDialogOpen(true)
  }

  const columns = createWebhooksColumns({
    onEdit: openEditDialog,
    onDelete: setDeletingWebhook
  })

  const activeFilterCount = [search, enabled, lastDelivery, createdAtFrom || createdAtTo].filter(
    Boolean
  ).length

  function handleSearch(value: string | null) {
    React.startTransition(() => {
      void setPageIndex(0)
      void setSearch(value)
    })
  }

  function handleClearAll() {
    React.startTransition(() => {
      void setPageIndex(0)
      void setSearch(null)
      void setFilters({
        enabled: null,
        lastDelivery: null,
        createdAtFrom: null,
        createdAtTo: null
      })
    })
  }

  const filters = [
    {
      key: 'enabled',
      label: 'Status',
      type: 'select' as const,
      value: enabled,
      options: [
        { label: 'Enabled', value: 'enabled' },
        { label: 'Disabled', value: 'disabled' }
      ]
    },
    {
      key: 'lastDelivery',
      label: 'Deliveries',
      type: 'select' as const,
      value: lastDelivery,
      options: [
        { label: 'Delivered', value: 'delivered' },
        { label: 'Failed', value: 'failed' },
        { label: 'Never delivered', value: 'never' }
      ]
    },
    {
      key: 'createdAt',
      label: 'Created',
      type: 'date-range' as const,
      from: createdAtFrom,
      to: createdAtTo
    }
  ]

  return (
    <React.Fragment>
      <PageHeader
        title="Webhooks"
        actions={
          <Button onClick={openCreateDialog}>
            <Plus className="size-3.5" />
            Add endpoint
          </Button>
        }
      />

      <EntityFiltersBar
        filters={filters}
        activeFilterCount={activeFilterCount}
        onFilterChange={(updates) => {
          React.startTransition(() => {
            void setPageIndex(0)
            void setFilters(updates)
          })
        }}
        onClearAll={handleClearAll}
        search={search}
        searchPlaceholder="Search webhooks..."
        isPending={isSearchFetching}
        onSearch={handleSearch}
      />
      <main className="flex-1 space-y-4 px-4 pb-4">
        <WebhooksTable
          columns={columns}
          search={search}
          enabled={enabled}
          lastDelivery={lastDelivery}
          createdAtFrom={createdAtFrom}
          createdAtTo={createdAtTo}
          onRowClick={openEditDialog}
        />
      </main>
      <WebhookEndpointDialog
        key={editingWebhook?.id ?? 'create'}
        webhook={editingWebhook}
        open={dialogOpen}
        onOpenChange={setDialogOpen}
      />
      <DeleteWebhookDialog
        webhook={deletingWebhook}
        open={deletingWebhook !== null}
        onOpenChange={(nextOpen) => {
          if (!nextOpen) setDeletingWebhook(null)
        }}
      />
    </React.Fragment>
  )
}
