"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 "./projects-table-columns"
import { getProjectListsForCover } from "../service"
import { Project } from "@/db/schema"
import { ProjectTableToolbarActions } from "./projects-table-toolbar-actions"
import { CoverTemplateDialog } from "./cover-template-dialog"

interface ItemsTableProps {
promises: Promise<
[
    Awaited<ReturnType<typeof getProjectListsForCover>>,
]
>
}

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

  console.log(data, 'data')

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

  // 템플릿 다이얼로그 상태
  const [templateDialogOpen, setTemplateDialogOpen] = React.useState(false)
  const [selectedProject, setSelectedProject] = React.useState<Project | null>(null)

  const handleTemplateManage = React.useCallback((project: Project) => {
    setSelectedProject(project)
    setTemplateDialogOpen(true)
  }, [])

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

  const filterFields: DataTableFilterField<Project>[] = []

  const advancedFilterFields: DataTableAdvancedFilterField<Project>[] = [
    {
      id: "code",
      label: "Project Code",
      type: "text",
    },
    {
      id: "name",
      label: "Project Name",
      type: "text",
    },
    {
      id: "createdAt",
      label: "Created At",
      type: "date",
    },
    {
      id: "updatedAt",
      label: "Updated At",
      type: "date",
    },
  ]

  const { table } = useDataTable({
    data,
    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,
  })

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <ProjectTableToolbarActions table={table} />
        </DataTableAdvancedToolbar>
      </DataTable>

      <CoverTemplateDialog
        open={templateDialogOpen}
        onOpenChange={setTemplateDialogOpen}
        project={selectedProject}
      />
    </>
  )
}