"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 { getColumns } from "./tech-vendors-table-columns"
import { getTechVendors, getTechVendorStatusCounts } from "../service"
import { TechVendor, techVendors } from "@/db/schema/techVendors"
import { TechVendorsTableToolbarActions } from "./tech-vendors-table-toolbar-actions"
import { UpdateVendorSheet } from "./update-vendor-sheet"
import { getVendorStatusIcon } from "../utils"
// import { ViewTechVendorLogsDialog } from "./view-tech-vendors-logs-dialog"

interface TechVendorsTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getTechVendors>>,
      Awaited<ReturnType<typeof getTechVendorStatusCounts>>
    ]
  >
}

export function TechVendorsTable({ promises }: TechVendorsTableProps) {
  // Suspense로 받아온 데이터
  const [{ data, pageCount }, statusCounts] = React.use(promises)
  const [isCompact, setIsCompact] = React.useState<boolean>(false) 

  const [rowAction, setRowAction] = React.useState<DataTableRowAction<TechVendor> | null>(null)
  
  // **router** 획득
  const router = useRouter()
  
  // getColumns() 호출 시, router를 주입
  const columns = React.useMemo(
    () => getColumns({ setRowAction, router }),
    [setRowAction, router]
  )
  
  // 상태 한글 변환 유틸리티 함수
  const getStatusDisplay = (status: string): string => {
    const statusMap: Record<string, string> = {
      "ACTIVE": "활성 상태",
      "INACTIVE": "비활성 상태",
      "BLACKLISTED": "거래 금지"
    };
    
    return statusMap[status] || status;
  };
  
  const filterFields: DataTableFilterField<TechVendor>[] = [
    {
      id: "status",
      label: "상태",
      options: techVendors.status.enumValues.map((status) => ({
        label: getStatusDisplay(status),
        value: status,
        count: statusCounts[status],
      })),
    },
    
    { id: "vendorCode", label: "업체 코드" },
  ]
  
  const advancedFilterFields: DataTableAdvancedFilterField<TechVendor>[] = [
    { id: "vendorName", label: "업체명", type: "text" },
    { id: "vendorCode", label: "업체코드", type: "text" },
    { id: "email", label: "이메일", type: "text" },
    { id: "country", label: "국가", type: "text" },
    {
      id: "status",
      label: "업체승인상태",
      type: "multi-select",
      options: techVendors.status.enumValues.map((status) => ({
        label: getStatusDisplay(status),
        value: status,
        count: statusCounts[status],
        icon: getVendorStatusIcon(status),
      })),
    },
    { id: "createdAt", label: "등록일", type: "date" },
    { id: "updatedAt", label: "수정일", 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,
  })

  const handleCompactChange = React.useCallback((compact: boolean) => {
    setIsCompact(compact)
  }, [])

  // 테이블 새로고침 핸들러
  const handleRefresh = React.useCallback(() => {
    router.refresh()
  }, [router])
  
  
  return (
    <>
      <DataTable
        table={table}
        compact={isCompact}
        // floatingBar={<TechVendorsTableFloatingBar table={table} />}
      >
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
          enableCompactToggle={true}
          compactStorageKey="techVendorsTableCompact"
          onCompactChange={handleCompactChange}
        >
          <TechVendorsTableToolbarActions table={table} onRefresh={handleRefresh} />
        </DataTableAdvancedToolbar>
      </DataTable>
      <UpdateVendorSheet
        open={rowAction?.type === "update"}
        onOpenChange={() => setRowAction(null)}
        vendor={rowAction?.row.original ?? null}
      />
    </>
  )
}