"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 { InfiniteDataTable } from "@/components/data-table/infinite-data-table"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { useFeatureFlags } from "./feature-flags-provider"
import { Button } from "@/components/ui/button"
import { RotateCcw, Info } from "lucide-react"
import { Alert, AlertDescription } from "@/components/ui/alert"

import { getItems } from "../service"
import { Item } from "@/db/schema/items"
import { getColumns } from "./items-table-columns"
import { ItemsTableToolbarActions } from "./items-table-toolbar-actions"
import { UpdateItemSheet } from "./update-item-sheet"
import { DeleteItemsDialog } from "./delete-items-dialog"
import { ViewModeToggle } from "@/components/data-table/view-mode-toggle"

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

export function ItemsTable({ promises }: ItemsTableProps) {
  const { featureFlags } = useFeatureFlags()

  // 페이지네이션 모드 데이터
  const paginationData = promises ? React.use(promises) : null
  const [{ data = [], pageCount = 0 }] = paginationData || [{ data: [], pageCount: 0 }]

  console.log('ItemsTable data:', data.length, 'items')

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

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

  // 기존 필터 필드들
  const filterFields: DataTableFilterField<Item>[] = [
    {
      id: "itemCode",
      label: "Item Code",
    },
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<Item>[] = [
    {
      id: "ProjectNo",
      label: "Project No",
      type: "text",
    },
    {
      id: "itemCode",
      label: "PKG Code(PK)",
      type: "text",
    },
    {
      id: "description",
      label: "PKG Code Decription",
      type: "text",
    },
    {
      id: "packageCode",
      label: "PKG Code",
      type: "text",
    },
    {
      id: "itemName",
      label: "패키지 이름",
      type: "text"
    },
    {
      id: "smCode",
      label: "SM Code",
      type: "text",
    },
   
  ]

  // 확장된 useDataTable 훅 사용 (pageSize 기반 자동 전환)
  const {
    table,
    infiniteScroll,
    isInfiniteMode,
    effectivePageSize,
    handlePageSizeChange,
    urlState
  } = 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,
    // 무한 스크롤 설정
    infiniteScrollConfig: {
      apiEndpoint: "/api/table/items/infinite",
      tableName: "items",
      maxPageSize: 100,
    },
  })

  // 새로고침 핸들러
  const handleRefresh = () => {
    if (isInfiniteMode && infiniteScroll) {
      infiniteScroll.refresh()
    } else {
      window.location.reload()
    }
  }

  return (
    <div className="w-full space-y-2.5 overflow-x-auto" style={{maxWidth:'100wv'}}>

        {/* 모드 토글 & 새로고침 */}
        <div className="flex items-center justify-between">
          <ViewModeToggle
            isInfiniteMode={isInfiniteMode}
            onSwitch={handlePageSizeChange}   // ← ViewModeToggle에 prop 추가
          />
        </div>

        {/* 에러 상태 (무한 스크롤 모드) */}
        {isInfiniteMode && infiniteScroll?.error && (
          <Alert variant="destructive">
            <AlertDescription>
              데이터를 불러오는 중 오류가 발생했습니다.
              <Button
                variant="link"
                size="sm"
                onClick={() => infiniteScroll.reset()}
                className="ml-2 p-0 h-auto"
              >
                다시 시도
              </Button>
            </AlertDescription>
          </Alert>
        )}

        {/* 로딩 상태가 아닐 때만 테이블 렌더링 */}
        {!(isInfiniteMode && infiniteScroll?.isLoading && infiniteScroll?.isEmpty) ? (
          <>
            {/* 도구 모음 */}
            <DataTableAdvancedToolbar
              table={table}
              filterFields={advancedFilterFields}
              shallow={false}
            >
              <ItemsTableToolbarActions table={table} />
            </DataTableAdvancedToolbar>

            {/* 테이블 렌더링 */}
            {isInfiniteMode ? (
              // 무한 스크롤 모드: InfiniteDataTable 사용 (자체 페이지네이션 없음)
              <InfiniteDataTable
                table={table}
                hasNextPage={infiniteScroll?.hasNextPage || false}
                isLoadingMore={infiniteScroll?.isLoadingMore || false}
                onLoadMore={infiniteScroll?.onLoadMore}
                totalCount={infiniteScroll?.totalCount}
                isEmpty={infiniteScroll?.isEmpty || false}
                compact={false}
                autoSizeColumns={true}
              />
            ) : (
              // 페이지네이션 모드: DataTable 사용 (내장 페이지네이션 활용)
              <DataTable
                table={table}
                compact={false}
                autoSizeColumns={true}
              />
            )}
          </>
        ) : (
          /* 로딩 스켈레톤 (무한 스크롤 초기 로딩) */
          <div className="space-y-3">
            <div className="text-sm text-muted-foreground mb-4">
              무한 스크롤 모드로 데이터를 로드하고 있습니다...
            </div>
            {Array.from({ length: 10 }).map((_, i) => (
              <div key={i} className="h-12 w-full bg-muted animate-pulse rounded" />
            ))}
          </div>
        )}

        {/* 기존 다이얼로그들 */}
        <UpdateItemSheet
          open={rowAction?.type === "update"}
          onOpenChange={() => setRowAction(null)}
          item={rowAction?.row.original ?? null}
        />
        <DeleteItemsDialog
          open={rowAction?.type === "delete"}
          onOpenChange={() => setRowAction(null)}
          items={rowAction?.row.original ? [rowAction?.row.original] : []}
          showTrigger={false}
          onSuccess={() => rowAction?.row.toggleSelected(false)}
        />
      </div>
      )
}