"use client"

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

import { toSentenceCase } from "@/lib/utils"
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 "./tag-table-column"
import { Tag } from "@/db/schema/vendorData"
import { DeleteTagsDialog } from "./delete-tags-dialog"
import { TagsTableToolbarActions } from "./tags-table-toolbar-actions"
import { TagsTableFloatingBar } from "./tags-table-floating-bar"
import { getTags } from "../service"
import { UpdateTagSheet } from "./update-tag-sheet"
import { useAtomValue } from 'jotai'
import { selectedModeAtom } from '@/atoms'

// 여기서 받은 `promises`로부터 태그 목록을 가져와 상태를 세팅
// 예: "selectedPackageId"는 props로 전달
interface TagsTableProps {
  promises: Promise< [ Awaited<ReturnType<typeof getTags>> ] >
  selectedPackageId: number
}

export function TagsTable({ promises, selectedPackageId }: TagsTableProps) {
  // 1) 데이터를 가져옴 (server component -> use(...) pattern)
  const [{ data, pageCount }] = React.use(promises)
  const selectedMode = useAtomValue(selectedModeAtom)

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

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

  // Filter fields
  const filterFields: DataTableFilterField<Tag>[] = [
    {
      id: "tagNo",
      label: "Tag Number",
      placeholder: "Filter Tag Number...",
    },
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<Tag>[] = [
    {
      id: "tagNo",
      label: "Tag No",
      type: "text",
    },
    {
      id: "tagType",
      label: "Tag Type",
      type: "text",
    },
    {
      id: "description",
      label: "Description",
      type: "text",
    },
    {
      id: "createdAt",
      label: "Created at",
      type: "date",
    },
    {
      id: "updatedAt",
      label: "Updated at",
      type: "date",
    },
  ]

  // 3) useDataTable 훅으로 react-table 구성
  const { table } = useDataTable({
    data: data,      // <-- 여기서 tableData 사용
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      // sorting: [{ id: "createdAt", desc: true }],
      columnPinning: { right: ["actions"] },
    },
    getRowId: (originalRow) => String(originalRow.id),
    shallow: false,
    clearOnDefault: true,
    columnResizeMode: "onEnd",

  })

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


  const handleCompactChange = React.useCallback((compact: boolean) => {
    setIsCompact(compact)
  }, [])
  
  
  return (
    <>
      <DataTable
        table={table}
        compact={isCompact}

        floatingBar={<TagsTableFloatingBar table={table} selectedPackageId={selectedPackageId}/>}
      >
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
          enableCompactToggle={true}
          compactStorageKey="tagTableCompact"
          onCompactChange={handleCompactChange}
        >
          {/*
            4) ToolbarActions에 tableData, setTableData 넘겨서
               import 시 상태 병합
          */}
          <TagsTableToolbarActions 
            table={table} 
            selectedPackageId={selectedPackageId}
            tableData={data}             // <-- pass current data
            selectedMode={selectedMode}
          />
        </DataTableAdvancedToolbar>
      </DataTable>

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


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