import { useState, useMemo } from 'react'
import { DataTable } from '@/components/DataTable'
import { Pagination } from '@/components/Pagination'
import { SearchSelect } from '@/components/SearchSelect'
import type { ReactNode } from 'react'

const DEFAULT_PAGE_SIZE = 20

interface FilterableTableProps {
  data: any[]
  columns: { key: string; label: string; align?: 'left' | 'right' | 'center'; render?: (row: any) => ReactNode }[]
  onRowClick?: (row: any) => void
  onRowDoubleClick?: (row: any) => void
  filterKey?: string
  filterLabel?: string
  sortOptions: { key: string; label: string }[]
  defaultSort?: string
  defaultOrder?: 'asc' | 'desc'
  statusFilterKey?: string
  statusFilterLabel?: string
  statusOptions?: { value: string; label: string }[]
  statusFilterValue?: string
  onStatusFilterChange?: (value: string) => void
  pageSize?: number
  serverSide?: boolean
  total?: number
  page?: number
  onPageChange?: (page: number) => void
  sort?: string
  order?: 'asc' | 'desc'
  onSortChange?: (sort: string) => void
  onOrderChange?: (order: 'asc' | 'desc') => void
  filter?: string
  onFilterChange?: (filter: string) => void
  filterButtons?: { key: string; label: string }[]
  filterOptions?: string[]
  searchKeys?: string[]
  searchPlaceholder?: string
  serverSearchValue?: string
  onServerSearchChange?: (value: string) => void
}

export function FilterableTable({
  data, columns, onRowClick, onRowDoubleClick,
  filterKey, filterLabel,
  sortOptions, defaultSort, defaultOrder = 'desc',
  statusFilterKey, statusFilterLabel, statusOptions, statusFilterValue, onStatusFilterChange,
  pageSize = DEFAULT_PAGE_SIZE,
  serverSide = false,
  total: serverTotal,
  page: serverPage,
  onPageChange,
  sort: serverSort,
  order: serverOrder,
  onSortChange,
  onOrderChange,
  filter: serverFilter,
  onFilterChange,
  filterButtons,
  filterOptions,
  searchKeys,
  searchPlaceholder,
  serverSearchValue,
  onServerSearchChange,
}: FilterableTableProps) {
  const [localPage, setLocalPage] = useState(1)
  const [localFilter, setLocalFilter] = useState('')
  const [localSort, setLocalSort] = useState(defaultSort || sortOptions[0]?.key || '')
  const [localOrder, setLocalOrder] = useState<'asc' | 'desc'>(defaultOrder)
  const [statusFilter, setStatusFilter] = useState('')
  const currentStatusFilter = serverSide ? (statusFilterValue ?? '') : statusFilter
  const [searchText, setSearchText] = useState('')

  const page = serverSide ? (serverPage ?? 1) : localPage
  const sort = serverSide ? (serverSort ?? localSort) : localSort
  const order = serverSide ? (serverOrder ?? localOrder) : localOrder
  const filter = serverSide ? (serverFilter ?? '') : localFilter

  const setPage = (p: number) => {
    if (serverSide) onPageChange?.(p)
    else setLocalPage(p)
  }
  const setSortVal = (s: string) => {
    if (serverSide) onSortChange?.(s)
    else setLocalSort(s)
    setPage(1)
  }
  const setOrderVal = (o: 'asc' | 'desc') => {
    if (serverSide) onOrderChange?.(o)
    else setLocalOrder(o)
    setPage(1)
  }
  const setFilterVal = (f: string) => {
    if (serverSide) onFilterChange?.(f)
    else setLocalFilter(f)
    setPage(1)
  }

  const filterValues = useMemo(() => {
    if (filterOptions) return filterOptions
    if (!filterKey) return []
    return [...new Set(data.map((r: any) => r[filterKey]).filter(Boolean))].sort() as string[]
  }, [data, filterKey, filterOptions])

  const filtered = useMemo(() => {
    if (serverSide) return data
    let r = data
    if (filter && filterKey) r = r.filter((row: any) => row[filterKey] === filter)
    if (currentStatusFilter && statusFilterKey) r = r.filter((row: any) => String(row[statusFilterKey]) === currentStatusFilter)
    if (searchText && searchKeys) r = r.filter((row: any) => searchKeys.some(k => String(row[k] ?? '').toLowerCase().includes(searchText.toLowerCase())))
    return [...r].sort((a: any, b: any) => {
      const av = parseFloat(a[sort]) || (typeof a[sort] === 'string' ? 0 : a[sort] || 0)
      const bv = parseFloat(b[sort]) || (typeof b[sort] === 'string' ? 0 : b[sort] || 0)
      return order === 'desc' ? bv - av : av - bv
    })
  }, [data, filter, filterKey, sort, order, currentStatusFilter, statusFilterKey, serverSide, searchText, searchKeys])

  const total = serverSide ? (serverTotal ?? 0) : filtered.length
  const paged = serverSide ? data : filtered.slice((page - 1) * pageSize, page * pageSize)

  return (
    <>
      <div className="mb-3 flex flex-wrap gap-2">
        {searchKeys && !serverSide && (
          <input
            type="text"
            placeholder={searchPlaceholder || '搜索...'}
            value={searchText}
            onChange={(e) => { setSearchText(e.target.value); setPage(1) }}
            className="rounded border px-3 py-1 text-sm"
          />
        )}
        {serverSide && onServerSearchChange && (
          <input
            type="text"
            placeholder={searchPlaceholder || '搜索...'}
            value={serverSearchValue ?? ''}
            onChange={(e) => { onServerSearchChange(e.target.value); setPage(1) }}
            className="rounded border px-3 py-1 text-sm"
          />
        )}
        {filterButtons ? (
          filterButtons.map(f => (
            <button key={f.key} onClick={() => setFilterVal(f.key)} className={`rounded px-3 py-1 text-xs ${filter === f.key ? 'bg-primary text-primary-foreground' : 'bg-muted'}`}>
              {f.label}
            </button>
          ))
        ) : filterKey && (
          <SearchSelect
            value={filter}
            onChange={setFilterVal}
            options={filterValues}
            emptyLabel={filterLabel || '全部'}
            className="min-w-[140px]"
          />
        )}
        {statusFilterKey && statusOptions && (
          <SearchSelect
            value={currentStatusFilter}
            onChange={(v) => { if (serverSide && onStatusFilterChange) { onStatusFilterChange(v) } else { setStatusFilter(v) }; setPage(1) }}
            options={statusOptions}
            emptyLabel={statusFilterLabel || '全部状态'}
            className="min-w-[120px]"
          />
        )}
        <span className="mx-1 text-muted-foreground">|</span>
        {sortOptions.map(s => (
          <button key={s.key} onClick={() => setSortVal(s.key)} className={`rounded px-3 py-1 text-xs ${sort === s.key ? 'bg-primary text-primary-foreground' : 'bg-muted'}`}>
            按{s.label}
          </button>
        ))}
        <span className="mx-1 text-muted-foreground">|</span>
        <button onClick={() => setOrderVal(order === 'asc' ? 'desc' : 'asc')} className="rounded bg-muted px-3 py-1 text-xs">
          {order === 'asc' ? '↑ 升序' : '↓ 降序'}
        </button>
      </div>
      <DataTable columns={columns} data={paged} onRowClick={onRowClick} onRowDoubleClick={onRowDoubleClick} />
      <Pagination page={page} pageSize={pageSize} total={total} onPageChange={setPage} />
    </>
  )
}
