import React, { useState, useRef, useImperativeHandle } from 'react'
import Search from '@/components/Search'
import TableList from '@/components/TableList'

export default React.forwardRef((props, ref) => {
  const tableRef = useRef()
  const searchRef = useRef()
  const [searchData, setSearchData] = useState({})
  const {api, searchFields, params, onPageChange,searchProps, ...leftProps} = props
  const handleSearch = (data) => setSearchData(data)

  useImperativeHandle(ref, () => ({
    reload: () => {
      if (tableRef.current) {
        tableRef.current.reload()
      }
    },
    getSearchData: searchData,
  }))

  return (
    <>
      <Search
        ref={searchRef}
        fields={searchFields}
        onSearch={handleSearch}
        onReset={handleSearch}
        searchProps={searchProps}
      />

      <TableList
        ref={tableRef}
        api={api}
        params={Object.assign(searchData, params||{})}
        {...leftProps}
        onPageChange={onPageChange}
      />
    </>
  )
})
