"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
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 { getProcurementItems } from "../service"
import { ProcurementItem } from "@/db/schema/items"
import { getColumns } from "./procurement-items-table-columns"
import { ProcurementItemsTableToolbarActions } from "./procurement-items-table-toolbar-actions"
import { UpdateProcurementItemSheet } from "./update-procurement-items-sheet"
import { DeleteProcurementItemsDialog } from "./delete-procurement-items-dialog"

interface ProcurementItemsTableProps {
  promises?: Promise<
    [
      Awaited<ReturnType<typeof getProcurementItems>>,
    ]
  >
}

export function ProcurementItemsTable({ promises }: ProcurementItemsTableProps) {
  // 페이지네이션 모드 데이터
  const paginationData = promises ? React.use(promises) : null
  const [{ data = [], pageCount = 0 }] = paginationData || [{ data: [], pageCount: 0 }]

  console.log('ProcurementItemsTable data:', data.length, 'items')

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

  const [isCompact, setIsCompact] = React.useState<boolean>(false)

  const router = useRouter()

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

  // 필터 필드들
  const filterFields: DataTableFilterField<ProcurementItem>[] = [
    {
      id: "itemCode",
      label: "품목코드",
    },
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<ProcurementItem>[] = [
    {
      id: "itemCode",
      label: "품목코드",
      type: "text",
    },
    {
      id: "itemName",
      label: "품목명",
      type: "text",
    },
    {
      id: "material",
      label: "재질",
      type: "text",
    },
    {
      id: "specification",
      label: "규격",
      type: "text",
    },
    {
      id: "unit",
      label: "단위",
      type: "text",
    },
    {
      id: "isActive",
      label: "활성화여부",
      type: "text",
    },
  ]

  const handleCompactChange = (compact: boolean) => {
    setIsCompact(compact)
  }

  // useDataTable 훅 사용
  const {table} = useDataTable({
    data: data,
    pageCount: pageCount,
    columns,
    filterFields,
    enableAdvancedFilter: true,
    initialState: {
      pageSize: 10,
      sorting: [{ id: "createdAt", desc: true }],
      columnVisibility: {
        id: false,
        updatedAt: false,
      },
    },
    getRowId: (originalRow) => String(originalRow.id),
    shallow: false,
    clearOnDefault: true,
  })

  return (
    <>
      <DataTable
        table={table}
        compact={isCompact}
      >
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
          enableCompactToggle={true}
          compactStorageKey="procurementItemsTableCompact"
          onCompactChange={handleCompactChange}
        >
          <ProcurementItemsTableToolbarActions
            table={table}
          />
        </DataTableAdvancedToolbar>
      </DataTable>

      <UpdateProcurementItemSheet
        open={rowAction?.type === "update"}
        onOpenChange={() => setRowAction(null)}
        procurementItem={rowAction?.row.original}
      />

      <DeleteProcurementItemsDialog
        open={rowAction?.type === "delete"}
        onOpenChange={() => setRowAction(null)}
        procurementItems={rowAction?.row.original ? [rowAction.row.original] : []}
        showTrigger={false}
        onSuccess={() => {
          setRowAction(null)
          router.refresh()
        }}
      />
    </>
  )
}
