import { useState, useImperativeHandle, forwardRef } from 'react'
import { Table, Form, Button, Space, Flex } from 'antd'
import type { TableProps } from 'antd'
import { useQuery } from '@tanstack/react-query'
import { debounce } from 'lodash-es'

export interface QueryParams {
  [key: string]: any
  page: number
  'per-page': number
}

export interface AppListProps extends TableProps {
  queryKey?: any[]
  fetchApi?: (params?: QueryParams) => Promise<{ list: any[]; total: number }>
  filters?: any[]
  filterAside?: React.ReactNode
}

export interface AppListRef {
  refresh: () => void
  reset: () => void
}

const AppList = forwardRef<AppListRef, AppListProps>(
  ({ queryKey = [], fetchApi, filters = [], filterAside, dataSource = [], ...props }, ref) => {
    const [form] = Form.useForm()
    const [queryParams, setQueryParams] = useState<QueryParams>({ page: 1, 'per-page': 10 })

    const { data, refetch, isLoading } = useQuery({
      queryKey: [...queryKey, 'appList', queryParams],
      queryFn: async () => {
        return fetchApi ? await fetchApi(queryParams) : { list: dataSource || [], total: dataSource?.length || 0 }
      },
      placeholderData: (): any => {
        return { list: dataSource || [], total: dataSource?.length || 0 }
      },
      enabled: !!fetchApi,
    })

    // 暴露方法
    useImperativeHandle(ref, () => ({
      refresh: refetch,
      reset: handleReset,
    }))

    // 提交筛选
    const handleSearch = (values: Record<string, any>) => {
      setQueryParams((prev) => ({ ...prev, ...values, page: 1 }))
    }
    const handleSearchDebounce = debounce(handleSearch, 500)

    const handleReset = () => {
      form.resetFields()
      setQueryParams({ page: 1, 'per-page': 10 })
    }

    // 处理分页
    const handlePageChange = (page: number, pageSize: number) => {
      setQueryParams((prev) => ({ ...prev, page, 'per-page': pageSize }))
    }

    const pagination = {
      hideOnSinglePage: true,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: [10, 20, 30, 40, 50],
      showTotal: (total: number) => `共${total}条数据`,
      onChange: handlePageChange,
    }

    const filterElement = (
      <div className="app-list-filter" style={{ marginBottom: 20 }}>
        <Flex justify="space-between">
          <Form
            layout="inline"
            autoComplete="off"
            form={form}
            onFinish={handleSearch}
            onValuesChange={handleSearchDebounce}>
            {filters.map((item, index) => (
              <Form.Item label={item.label} name={item.name} key={index} style={{ minWidth: 140 }}>
                {item.element}
              </Form.Item>
            ))}
            <Space>
              <Button type="primary" htmlType="button" ghost onClick={handleReset}>
                重置
              </Button>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Space>
          </Form>
          {filterAside}
        </Flex>
      </div>
    )

    return (
      <div className="app-list">
        {filters.length > 0 && filterElement}
        <div className="app-list-table">
          <Table bordered rowKey="id" dataSource={data?.list} loading={isLoading} pagination={pagination} {...props} />
        </div>
      </div>
    )
  }
)

export default AppList
