"use client"

import * as React from "react"
import { type GtcClauseTreeView } from "@/db/schema/gtc"
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 type {
  getGtcClauses,
  getUsersForFilter
} from "@/lib/gtc-contract/gtc-clauses/service"
import { getColumns } from "./gtc-clauses-table-columns"
import { GtcClausesTableToolbarActions } from "./gtc-clauses-table-toolbar-actions"
import { DeleteGtcClausesDialog } from "./delete-gtc-clauses-dialog"
import { GtcClausesTableFloatingBar } from "./gtc-clauses-table-floating-bar"
import { UpdateGtcClauseSheet } from "./update-gtc-clause-sheet"
import { CreateGtcClauseDialog } from "./create-gtc-clause-dialog"
import { ReorderGtcClausesDialog } from "./reorder-gtc-clauses-dialog"
import { BulkUpdateGtcClausesDialog } from "./bulk-update-gtc-clauses-dialog"
import { GenerateVariableNamesDialog } from "./generate-variable-names-dialog"
import { DuplicateGtcClauseDialog } from "./duplicate-gtc-clause-dialog"
import { ClauseVariableSettingsDialog } from "./clause-variable-settings-dialog"
import { ViewClauseVariablesDialog } from "./view-clause-variables-dialog"

interface GtcClausesTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getGtcClauses>>,
      Awaited<ReturnType<typeof getUsersForFilter>>
    ]
  >
  documentId: number
  document: any
}

export function GtcClausesTable({ promises, documentId, document }: GtcClausesTableProps) {
  const [{ data, pageCount }, users] = React.use(promises)

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

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

  /**
   * Filter fields for the data table.
   */
  const filterFields: DataTableFilterField<GtcClauseTreeView>[] = [
    {
      id: "itemNumber",
      label: "채번",
      placeholder: "채번으로 검색...",
    },
    {
      id: "subtitle",
      label: "소제목",
      placeholder: "소제목으로 검색...",
    },
    {
      id: "content",
      label: "상세항목",
      placeholder: "상세항목으로 검색...",
    },
  ]

  /**
   * Advanced filter fields for the data table.
   */
  const advancedFilterFields: DataTableAdvancedFilterField<GtcClauseTreeView>[] = [
    {
      id: "itemNumber",
      label: "채번",
      type: "text",
    },
    {
      id: "category",
      label: "분류",
      type: "text",
    },
    {
      id: "subtitle",
      label: "소제목",
      type: "text",
    },
    {
      id: "content",
      label: "상세항목",
      type: "text",
    },
    {
      id: "depth",
      label: "계층 깊이",
      type: "multi-select",
      options: [
        { label: "1단계", value: "0" },
        { label: "2단계", value: "1" },
        { label: "3단계", value: "2" },
        { label: "4단계", value: "3" },
        { label: "5단계", value: "4" },
      ],
    },
    {
      id: "createdByName",
      label: "작성자",
      type: "multi-select",
      options: users.map((user) => ({
        label: user.name,
        value: user.name,
      })),
    },
    {
      id: "updatedByName",
      label: "수정자", 
      type: "multi-select",
      options: users.map((user) => ({
        label: user.name,
        value: user.name,
      })),
    },
    {
      id: "createdAt",
      label: "작성일",
      type: "date",
    },
    {
      id: "updatedAt",
      label: "수정일",
      type: "date",
    },
  ]

  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{"id":"itemNumber","desc":false}],
      columnPinning: { right: ["actions"] },
    },
    getRowId: (originalRow) => `${originalRow.id}`,
    shallow: false,
    clearOnDefault: true,
  })

  return (
    <>
      <DataTable
        table={table}
        // floatingBar={<GtcClausesTableFloatingBar table={table} />}
      >
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <GtcClausesTableToolbarActions 
            table={table} 
            documentId={documentId}
            document={document}
          />
        </DataTableAdvancedToolbar>
      </DataTable>

      {/* 삭제 다이얼로그 */}
      <DeleteGtcClausesDialog
        open={rowAction?.type === "delete"}
        onOpenChange={() => setRowAction(null)}
        gtcClauses={rowAction?.row.original ? [rowAction?.row.original] : []}
        showTrigger={false}
        onSuccess={() => rowAction?.row.toggleSelected(false)}
      />

      {/* 수정 시트 */}
      <UpdateGtcClauseSheet
        open={rowAction?.type === "update"}
        onOpenChange={() => setRowAction(null)}
        gtcClause={rowAction?.row.original ?? null}
        documentId={documentId}
      />

      {/* 생성 다이얼로그 */}
      {/* <CreateGtcClauseDialog 
        key="main-create"
        documentId={documentId}
        document={document}
      /> */}

      {/* 하위 조항 추가 다이얼로그 */}
      <CreateGtcClauseDialog 
        key={`sub-create-${rowAction?.row.original.id || 'none'}`}
        documentId={documentId}
        document={document}
        parentClause={rowAction?.type === "addSubClause" ? rowAction.row.original : null}
        open={rowAction?.type === "addSubClause"}
        onOpenChange={(open) => {
          if (!open) {
            setRowAction(null)
          }
        }}
        showTrigger={false}
        onSuccess={() => {
          setRowAction(null)
          // 테이블 리프레시 로직
        }}
      />

      {/* 조항 복제 다이얼로그 */}
      <DuplicateGtcClauseDialog
        open={rowAction?.type === "duplicate"}
        onOpenChange={() => setRowAction(null)}
        sourceClause={rowAction?.row.original ?? null}
        onSuccess={() => {
          // 테이블 리프레시 로직
        }}
      />


    </>
  )
}