"use client"

import * as React from "react"
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 type { DataTableAdvancedFilterField, DataTableRowAction } from "@/types/table"
import { getDocumentClassCodeGroups } from "@/lib/docu-list-rule/document-class/service"
import { getColumns } from "./document-class-table-columns"
import { DocumentClassEditSheet } from "./document-class-edit-sheet"
import { DocumentClassOptionsTable } from "./document-class-options-table"
import { DocumentClassTableToolbarActions } from "./document-class-table-toolbar"
import { DeleteDocumentClassDialog } from "./delete-document-class-dialog"
import { documentClasses } from "@/db/schema/docu-list-rule"

interface DocumentClassTableProps {
  promises?: Promise<[{ data: typeof documentClasses.$inferSelect[]; pageCount: number }]>
}

export function DocumentClassTable({ promises }: DocumentClassTableProps) {
  const rawData = React.use(promises!)
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<typeof documentClasses.$inferSelect> | null>(null)
  const [selectedDocumentClass, setSelectedDocumentClass] = React.useState<typeof documentClasses.$inferSelect | null>(null)

  const refreshData = React.useCallback(() => {
    window.location.reload()
  }, [])

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

  // 고급 필터 필드 설정
  const advancedFilterFields: DataTableAdvancedFilterField<typeof documentClasses.$inferSelect>[] = [
    { id: "code", label: "코드", type: "text" },
    { id: "value", label: "값", type: "text" },
    { id: "description", label: "설명", type: "text" },
    { id: "createdAt", label: "생성일", type: "date" },
  ]

  const { table } = useDataTable({
    data: rawData[0].data as any,
    columns,
    pageCount: rawData[0].pageCount,
    enablePinning: true,
    enableAdvancedFilter: true,
    manualSorting: false,
    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}
        >
          <DocumentClassTableToolbarActions table={table} onSuccess={refreshData} />
        </DataTableAdvancedToolbar>
      </DataTable>

      {/* 구분선 */}
      <div className="border-t border-border my-6"></div>

      {/* Document Class 옵션 관리 제목 */}
      <div className="flex items-center justify-between space-y-2">
        <div>
          <div className="flex items-center gap-2">
            <h2 className="text-2xl font-bold tracking-tight">Document Class 옵션 관리</h2>
          </div>
          <p className="text-muted-foreground">
            Document Class 옵션들을 관리합니다.
          </p>
        </div>
      </div>

      {/* Document Class 옵션 테이블 */}
      <DocumentClassOptionsTable 
        selectedDocumentClass={selectedDocumentClass}
        documentClasses={rawData[0].data || []}
        onSelectDocumentClass={setSelectedDocumentClass}
      />

      <DeleteDocumentClassDialog
        open={rowAction?.type === "delete"}
        onOpenChange={() => setRowAction(null)}
        documentClasses={rowAction?.row.original ? [rowAction?.row.original] : []}
        showTrigger={false}
        onSuccess={() => {
          rowAction?.row.toggleSelected(false)
          refreshData()
        }}
      />

      <DocumentClassEditSheet
        open={rowAction?.type === "update"}
        onOpenChange={() => setRowAction(null)}
        data={rowAction?.row.original ?? null}
        onSuccess={refreshData}
      />
    </>
  )
} 