"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 { TemplateTableToolbarActions } from "./template-table-toolbar-actions"
import { getColumns } from "./template-table-columns"
import { type TemplateListView } from "@/db/schema"
import { getTemplateList } from "../service"
import { UpdateTemplateSheet } from "./update-template-sheet"
import { CreateTemplateSheet } from "./create-template-sheet"
import DuplicateTemplateSheet from './duplicate-template-sheet';
import { DeleteTemplateDialog } from "./delete-template-dialog"

interface TemplateTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getTemplateList>>,
    ]
  >
}

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

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

  const [showCreateSheet, setShowCreateSheet] = React.useState(false)

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

  /**
   * 기본 필터 필드 (드롭다운 형태)
   */
  const filterFields: DataTableFilterField<TemplateListView>[] = [

  ]

  /**
   * 고급 필터 필드 (검색, 날짜 등)
   */
  const advancedFilterFields: DataTableAdvancedFilterField<TemplateListView>[] = [
    {
      id: "name",
      label: "템플릿 이름",
      type: "text",
    },
    {
      id: "slug", 
      label: "Slug",
      type: "text",
    },

    {
      id: "variableCount",
      label: "변수 개수",
      type: "text",
    },
    {
      id: "version",
      label: "버전",
      type: "text", 
    },
    {
      id: "createdAt",
      label: "생성일",
      type: "date",
    },
    {
      id: "updatedAt",
      label: "수정일",
      type: "date",
    },
  ]

  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: "updatedAt", desc: true }],
      columnPinning: { right: ["actions"] },
      columnVisibility: {
        slug: false, // 기본적으로 slug 컬럼은 숨김
      },
    },
    getRowId: (originalRow) => String(originalRow.id),
    shallow: false,
    clearOnDefault: true,
  })

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <TemplateTableToolbarActions 
            table={table} 
            onCreateTemplate={() => setShowCreateSheet(true)}
          />
        </DataTableAdvancedToolbar>
      </DataTable>

      {/* 새 템플릿 생성 Sheet */}
      <CreateTemplateSheet
        open={showCreateSheet}
        onOpenChange={setShowCreateSheet}
      />

      {/* 템플릿 수정 Sheet */}
      <UpdateTemplateSheet
        open={rowAction?.type === "update"}
        onOpenChange={() => setRowAction(null)}
        template={rowAction?.type === "update" ? rowAction.row.original : null}
      />

      {/* 템플릿 복제 Sheet */}
      <DuplicateTemplateSheet
        open={rowAction?.type === "duplicate"}
        onOpenChange={() => setRowAction(null)}
        template={rowAction?.type === "duplicate" ? rowAction.row.original : null}
      />

      {/* 템플릿 삭제 Dialog */}
      <DeleteTemplateDialog
        open={rowAction?.type === "delete"}
        onOpenChange={() => setRowAction(null)}
        templates={rowAction?.type === "delete" ? [rowAction.row.original] : []}
        showTrigger={false}
        onSuccess={() => {
          setRowAction(null)
          // 테이블 새로고침은 server action에서 자동으로 처리됨
        }}
      />
    </>
  )
}