import React from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { AgGridReact } from 'ag-grid-react'
import { useMessage } from '@/hooks/useMessage'

import 'ag-grid-community/styles/ag-grid.css'
import 'ag-grid-community/styles/ag-theme-quartz.css'

export default function PlanRequestPopQGrid(props) {
  const { getMessage } = useMessage()

  const { gridData, gridColumns, isPageable = true } = props

  const [rowData, setRowData] = useState(null)

  const [gridApi, setGridApi] = useState(null)

  const [colDefs, setColDefs] = useState(gridColumns)

  const defaultColDef = useMemo(() => {
    return {
      flex: 1,
      minWidth: 100,
      sortable: false,
      suppressMovable: false,
      resizable: false,
      suppressSizeToFit: false,
    }
  }, [])

  const rowBuffer = 20

  useEffect(() => {
    gridData ? setRowData(gridData) : ''
  }, [gridData])

  const onGridReady = useCallback(
    (params) => {
      setGridApi(params.api)
      gridData ? setRowData(gridData) : ''
    },
    [gridData],
  )

  //부모로 선택한 설계의뢰정보 보내기
  const onSelectionChanged = () => {
    const selectedData = gridApi.getSelectedRows()
    props.getSelectedRowdata(selectedData)
  }

  return (
    <div className="ag-theme-quartz" style={{ height: 350 }}>
      <AgGridReact
        onGridReady={onGridReady}
        rowBuffer={rowBuffer}
        rowData={rowData}
        columnDefs={colDefs}
        defaultColDef={defaultColDef}
        rowSelection={'singleRow'}
        pagination={isPageable}
        onSelectionChanged={onSelectionChanged}
        overlayNoRowsTemplate={`<span className="ag-overlay-loading-center">${getMessage('stuff.grid.noData')}</span>`}
      />
    </div>
  )
}
