"use client"

import * as React from "react"
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
  DataTableRowAction,
} from "@/types/table"

import { useDataTable } from "@/hooks/use-data-table"
import { DataTable } from "@/components/data-table/data-table"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"

import { getColumns } from "./whitelist-table-columns"
import { type EmailWhitelist } from "../service"
import { getEmailWhitelistList } from "../service"
import { UpdateWhitelistDialog } from "./update-whitelist-dialog"
import { CreateWhitelistDialog } from "./create-whitelist-dialog"
import { DeleteWhitelistDialog } from "./delete-whitelist-dialog"

interface WhitelistTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getEmailWhitelistList>>,
    ]
  >
}

export function WhitelistTable({ promises }: WhitelistTableProps) {
  const [{ data, pageCount }] = React.use(promises)

  const [rowAction, setRowAction] =
    React.useState<DataTableRowAction<EmailWhitelist> | null>(null)

  const [showCreateDialog, setShowCreateDialog] = React.useState(false)

  const columns = React.useMemo(
    () => getColumns({ setRowAction }),
    [setRowAction]
  )

  /**
   * 기본 필터 필드 (드롭다운 형태)
   */
  const filterFields: DataTableFilterField<EmailWhitelist>[] = []

  /**
   * 고급 필터 필드 (검색, 날짜 등)
   */
  const advancedFilterFields: DataTableAdvancedFilterField<EmailWhitelist>[] = [
    {
      id: "displayValue",
      label: "이메일/도메인",
      type: "text",
    },
    {
      id: "description",
      label: "설명",
      type: "text",
    },
    {
      id: "createdAt",
      label: "생성일",
      type: "date",
    },
    {
      id: "updatedAt",
      label: "수정일",
      type: "date",
    },
  ]

  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    filterFields,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: "createdAt", desc: true }],
      columnPinning: { right: ["actions"] },
    },
    getRowId: (originalRow) => String(originalRow.id),
    shallow: false,
    clearOnDefault: true,
  })

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <CreateWhitelistDialog
            open={showCreateDialog}
            onOpenChange={setShowCreateDialog}
          />
          <button
            type="button"
            className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50"
            onClick={() => setShowCreateDialog(true)}
          >
            이메일/도메인 추가
          </button>
        </DataTableAdvancedToolbar>
      </DataTable>

      {/* 도메인 수정 Dialog */}
      <UpdateWhitelistDialog
        open={rowAction?.type === "update"}
        onOpenChange={() => setRowAction(null)}
        whitelist={rowAction?.type === "update" ? rowAction.row.original : null}
      />

      {/* 도메인 삭제 Dialog */}
      <DeleteWhitelistDialog
        open={rowAction?.type === "delete"}
        onOpenChange={() => setRowAction(null)}
        whitelists={rowAction?.type === "delete" ? [rowAction.row.original] : []}
        showTrigger={false}
        onSuccess={() => {
          setRowAction(null)
          // 테이블 새로고침은 server action에서 자동으로 처리됨
        }}
      />
    </>
  )
}
