"use client"

import * as React from "react"
import type { DataTableAdvancedFilterField } from "@/types/table"
import { type Table } from "@tanstack/react-table"
import { LayoutGrid, TableIcon } from "lucide-react" 
import { Button } from "@/components/ui/button"

import { cn } from "@/lib/utils"
import { DataTableFilterList } from "@/components/data-table/data-table-filter-list" // ✅ 확장된 버전 사용
import { DataTableSortList } from "@/components/data-table/data-table-sort-list"
import { DataTableViewOptions } from "@/components/data-table/data-table-view-options"
import { DataTablePinList } from "./data-table-pin"
import { PinLeftButton } from "./data-table-pin-left"
import { PinRightButton } from "./data-table-pin-right"
import { DataTableGlobalFilter } from "./data-table-grobal-filter"
import { DataTableGroupList } from "./data-table-group-list"

// 로컬 스토리지 사용을 위한 훅
const useLocalStorage = <T,>(key: string, initialValue: T): [T, (value: T | ((val: T) => T)) => void] => {
  const [storedValue, setStoredValue] = React.useState<T>(() => {
    if (typeof window === "undefined") {
      return initialValue
    }
    try {
      const item = window.localStorage.getItem(key)
      return item ? JSON.parse(item) : initialValue
    } catch (error) {
      console.error(error)
      return initialValue
    }
  })

  const setValue = (value: T | ((val: T) => T)) => {
    try {
      const valueToStore = value instanceof Function ? value(storedValue) : value
      setStoredValue(valueToStore)
      if (typeof window !== "undefined") {
        window.localStorage.setItem(key, JSON.stringify(valueToStore))
      }
    } catch (error) {
      console.error(error)
    }
  }

  return [storedValue, setValue]
}

interface DataTableAdvancedToolbarProps<TData>
  extends React.HTMLAttributes<HTMLDivElement> {
  /**
   * The table instance returned from useDataTable hook with pagination, sorting, filtering, etc.
   * @type Table<TData>
   */
  table: Table<TData>

  /**
   * An array of filter field configurations for the data table.
   * @type DataTableAdvancedFilterField<TData>[]
   */
  filterFields: DataTableAdvancedFilterField<TData>[]

  /**
   * Debounce time (ms) for filter updates to enhance performance during rapid input.
   * @default 300
   */
  debounceMs?: number

  /**
   * Shallow mode keeps query states client-side, avoiding server calls.
   * Setting to `false` triggers a network request with the updated querystring.
   * @default true
   */
  shallow?: boolean

  /**
   * 컴팩트 모드를 사용할지 여부 (토글 버튼을 숨기려면 null)
   * @default true
   */
  enableCompactToggle?: boolean | null

  /**
   * 초기 컴팩트 모드 상태
   * @default false
   */
  initialCompact?: boolean

  /**
   * 컴팩트 모드가 변경될 때 호출될 콜백 함수
   */
  onCompactChange?: (isCompact: boolean) => void

  /**
   * 컴팩트 모드 상태를 저장할 로컬 스토리지 키
   * @default "dataTableCompact"
   */
  compactStorageKey?: string

  // ✅ 외부 필터 지원을 위한 새로운 props
  /**
   * 외부에서 전달받은 필터 (예: 폼에서 생성된 필터)
   */
  externalFilters?: any[]

  /**
   * 외부에서 전달받은 조인 연산자
   */
  externalJoinOperator?: "and" | "or"

  /**
   * 필터 변경 시 호출될 콜백
   */
  onFiltersChange?: (filters: any[], joinOperator: "and" | "or") => void
}

export function DataTableAdvancedToolbar<TData>({
  table,
  filterFields = [],
  debounceMs = 300,
  shallow = true,
  enableCompactToggle = true,
  initialCompact = false,
  onCompactChange,
  compactStorageKey = "dataTableCompact",
  externalFilters,
  externalJoinOperator,
  onFiltersChange,
  children,
  className,
  ...props
}: DataTableAdvancedToolbarProps<TData>) {
  // 컴팩트 모드 상태 관리
  const [isCompact, setIsCompact] = useLocalStorage<boolean>(
    compactStorageKey,
    initialCompact
  )

  // 컴팩트 모드 변경 시 콜백 호출
  React.useEffect(() => {
    onCompactChange?.(isCompact)
  }, [isCompact, onCompactChange])

  // 컴팩트 모드 토글 핸들러
  const handleToggleCompact = React.useCallback(() => {
    setIsCompact(prev => !prev)
  }, [setIsCompact])

  return (
    <div
      className={cn(
        "flex w-full items-center justify-between gap-2 overflow-auto p-1",
        className
      )}
      {...props}
    >
      <div className="flex items-center gap-2">
        {enableCompactToggle && (
          <Button
            variant="outline"
            size="sm"
            onClick={handleToggleCompact}
            title={isCompact ? "확장 보기로 전환" : "컴팩트 보기로 전환"}
            className="h-8 px-2"
          >
            {isCompact ? <LayoutGrid size={16} /> : <TableIcon size={16} />}
          </Button>
        )}
        <DataTableViewOptions table={table} />
        
        {/* ✅ 확장된 DataTableFilterList 사용 */}
        <DataTableFilterList
          table={table}
          filterFields={filterFields}
          debounceMs={debounceMs}
          shallow={shallow}
          externalFilters={externalFilters}
          externalJoinOperator={externalJoinOperator}
          onFiltersChange={onFiltersChange}
        />
        
        <DataTableSortList
          table={table}
          debounceMs={debounceMs}
          shallow={shallow}
        />
        <DataTableGroupList table={table} debounceMs={debounceMs} />
        <PinLeftButton table={table} />
        <PinRightButton table={table} />
        <DataTableGlobalFilter />
      </div>
      <div className="flex items-center gap-2">
        {children}
      </div>
    </div>
  )
}