"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 { useFeatureFlags } from "./feature-flags-provider"
import { getColumns } from "./vendors-table-columns"
import { getVendors, getVendorStatusCounts } from "../service"
import { VendorWithType, vendors } from "@/db/schema/vendors"
import { VendorsTableToolbarActions } from "./vendors-table-toolbar-actions"
import { UpdateVendorSheet } from "./update-vendor-sheet"
import { getVendorStatusIcon } from "@/lib/vendors/utils"
import { ViewVendorLogsDialog } from "./view-vendors_logs-dialog"
import { useSession } from "next-auth/react"

interface VendorsTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getVendors>>,
      Awaited<ReturnType<typeof getVendorStatusCounts>>
    ]
  >
}

export function VendorsTable({ promises }: VendorsTableProps) {
  const { data: session } = useSession()
  const userId = Number(session?.user.id) 
  
  // Suspense로 받아온 데이터
  const [{ data, pageCount }, statusCounts] = React.use(promises)
  const [isCompact, setIsCompact] = React.useState<boolean>(false) 

  const [rowAction, setRowAction] = React.useState<DataTableRowAction<VendorWithType> | null>(null)
  
  // **router** 획득
  const router = useRouter()
  
  // getColumns() 호출 시, router를 주입
  const columns = React.useMemo(
    () => getColumns({ setRowAction, router , userId}),
    [setRowAction, router, userId]
  )
  
  // 상태 한글 변환 유틸리티 함수
  const getStatusDisplay = (status: string): string => {
    const statusMap: Record<string, string> = {
      "PENDING_REVIEW": "가입 신청 중",
      "IN_REVIEW": "심사 중", 
      "REJECTED": "심사 거부됨",
      "IN_PQ": "PQ 진행 중",
      "PQ_SUBMITTED": "PQ 제출",
      "PQ_FAILED": "PQ 실패", 
      "PQ_APPROVED": "PQ 통과",
      "APPROVED": "승인됨",
      "READY_TO_SEND": "MDG 송부대기",
      "ACTIVE": "활성 상태",
      "INACTIVE": "비활성 상태",
      "BLACKLISTED": "거래 금지"
    };
    
    return statusMap[status] || status;
  };
  
  const filterFields: DataTableFilterField<VendorWithType>[] = [
    {
      id: "status",
      label: "상태",
      options: vendors.status.enumValues.map((status) => ({
        label: getStatusDisplay(status),
        value: status,
        count: statusCounts[status],
      })),
    },
    
    { id: "vendorCode", label: "업체 코드" },
  ]
  
  const advancedFilterFields: DataTableAdvancedFilterField<VendorWithType>[] = [
    { 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: vendors.status.enumValues.map((status) => ({
        label: getStatusDisplay(status),
        value: status,
        count: statusCounts[status],
        icon: getVendorStatusIcon(status),
      })),
    },
    { id: "vendorTypeName", label: "업체 유형", type: "text" },
    { id: "vendorCategory", label: "업체 분류", type: "select", options: [
      { label: "정규업체", value: "정규업체" },
      { label: "잠재업체", value: "잠재업체" },
    ]},
    { id: "createdAt", label: "등록일", type: "date" },
    { id: "updatedAt", label: "수정일", type: "date" },
  ]
  
  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    enableMultiRowSelection: false, // 단일 선택 모드로 제한
    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)
  }, [])
  
  
  return (
    <>
      <DataTable
        table={table}
        compact={isCompact}
        // floatingBar={<VendorsTableFloatingBar table={table} />}
      >
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
          enableCompactToggle={true}
          compactStorageKey="vendorsTableCompact"
          onCompactChange={handleCompactChange}
        >
          <VendorsTableToolbarActions table={table} />
        </DataTableAdvancedToolbar>
      </DataTable>
      <UpdateVendorSheet
        open={rowAction?.type === "update"}
        onOpenChange={() => setRowAction(null)}
        vendor={rowAction?.row.original ?? null}
      />
      
      <ViewVendorLogsDialog
        open={rowAction?.type === "log"}
        onOpenChange={() => setRowAction(null)}
        vendorId={rowAction?.row.original?.id ?? null}
      />
    </>
  )
}