"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
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 { getColumns } from "@/lib/docu-list-rule/document-class/table/document-class-table-columns"
import { DocumentClassEditSheet } from "@/lib/docu-list-rule/document-class/table/document-class-edit-sheet"
import { DocumentClassOptionsDetailSheet } from "@/lib/docu-list-rule/document-class/table/document-class-options-detail-sheet"
import { DocumentClassTableToolbarActions } from "@/lib/docu-list-rule/document-class/table/document-class-table-toolbar"
import { DeleteDocumentClassDialog } from "@/lib/docu-list-rule/document-class/table/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 router = useRouter()
  const rawData = React.use(promises!)
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<typeof documentClasses.$inferSelect> | null>(null)
  const [isDetailSheetOpen, setIsDetailSheetOpen] = React.useState(false)
  const [selectedDocumentClass, setSelectedDocumentClass] = React.useState<typeof documentClasses.$inferSelect | null>(null)

  const refreshData = React.useCallback(() => {
    router.refresh()
  }, [router])

  // Detail 버튼 클릭 핸들러
  const handleDetail = React.useCallback((documentClass: typeof documentClasses.$inferSelect) => {
    setSelectedDocumentClass(documentClass)
    setIsDetailSheetOpen(true)
  }, [])

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

  // 고급 필터 필드 설정
  const advancedFilterFields: DataTableAdvancedFilterField<typeof documentClasses.$inferSelect>[] = [
    { id: "value", label: "DOC_CLASS", type: "text" },
    { id: "description", label: "Description", type: "text" },
    { id: "createdAt", label: "createdAt", type: "date" },
  ]

  const { table } = useDataTable({
    data: rawData[0]?.data as typeof documentClasses.$inferSelect[] || [],
    columns,
    pageCount: rawData[0]?.pageCount || 0,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      columnPinning: { right: ["actions"] },
    },
    getRowId: (originalRow) => String(originalRow.id),
    shallow: false,
    clearOnDefault: true,
  })




  // 정렬 시 펼쳐진 상태 유지
  React.useEffect(() => {
    const currentExpanded = table.getState().expanded
    if (Object.keys(currentExpanded).length > 0) {
      // 약간의 지연 후 현재 펼쳐진 상태를 다시 설정
      const timer = setTimeout(() => {
        table.setExpanded(currentExpanded)
      }, 100)
      return () => clearTimeout(timer)
    }
  }, [table.getState().sorting, table])

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
        >
          <DocumentClassTableToolbarActions table={table} onSuccess={refreshData} />
        </DataTableAdvancedToolbar>
      </DataTable>

      {/* Detail 시트 */}
      <DocumentClassOptionsDetailSheet
        open={isDetailSheetOpen}
        onOpenChange={setIsDetailSheetOpen}
        documentClass={selectedDocumentClass}
        onSuccess={() => {
          setIsDetailSheetOpen(false)
          setSelectedDocumentClass(null)
        }}
      />

      <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}
      />
    </>
  )
} 