'use client'

import React, { useEffect, useState, useRef } from 'react'
import { useRouter, usePathname } from 'next/navigation'
import { Button } from '@nextui-org/react'
import { useAxios } from '@/hooks/useAxios'
import { QToast } from '@/hooks/useToast'
import StuffQGrid from './StuffQGrid'
import { useI18n } from '@/locales/client'
import { useRecoilValue } from 'recoil'
import { stuffSearchState } from '@/store/stuffAtom'
import { queryStringFormatter } from '@/util/common-utils'
import dayjs from 'dayjs'
import isLeapYear from 'dayjs/plugin/isLeapYear' // 윤년 판단 플러그인
dayjs.extend(isLeapYear)

export default function Stuff() {
  const stuffSearchParams = useRecoilValue(stuffSearchState)

  const { get, del } = useAxios()
  const gridRef = useRef()
  const lang = useI18n()

  const [gridCount, setGridCount] = useState(0)
  const [selectedRowData, setSelectedRowData] = useState([])
  const [selectedRowDataCount, setSelectedRowDataCount] = useState(0)

  const router = useRouter()
  const pathname = usePathname()

  //그리드 내부 복사버튼
  const copyNo = async (value) => {
    try {
      await navigator.clipboard.writeText(value)
      QToast({
        message: `${value}물건번호가 복사되었습니다`,
        type: 'info',
      })
    } catch (error) {
      QToast({
        message: `클립보드 복사에 실패하였습니다`,
        type: 'error',
      })
    }
  }

  const [gridProps, setGridProps] = useState({
    gridData: [],
    isPageable: false,
    // sets 10 rows per page (default is 100)
    paginationPageSize: 100,
    // allows the user to select the page size from a predefined list of page sizes
    paginationPageSizeSelector: [100, 200, 300, 400],
    gridColumns: [
      {
        field: 'lastEditDatetime',
        headerName: lang('stuff.gridHeader.lastEditDatetime'),
        headerCheckboxSelection: true,
        headerCheckboxSelectionCurrentPageOnly: true, //페이징시 현재 페이지만 체크되도록
        checkboxSelection: true,
        showDisabledCheckboxes: true,
        // headerClass: 'centered', //_test.scss에 추가 테스트
        // .centered {
        //   .ag-header-cell-label {
        //     justify-content: center !important;
        //   }
        // }
        cellStyle: { textAlign: 'center' },
        //suppressMovable: true, //헤더 못움직이게
        // width : 100
        // minWidth : 100
        // maxWidth : 100
        valueFormatter: function (params) {
          if (params.value) {
            return dayjs(params?.value).format('YYYY.MM.DD HH:mm:ss')
          } else {
            return null
          }
        },
      },
      {
        field: 'objectNo',
        headerName: lang('stuff.gridHeader.objectNo'),
        // headerClass: 'centered', //_test.scss에 추가 테스트
        cellRenderer: function (params) {
          if (params.data.objectNo) {
            return (
              <div>
                <Button
                  size="sm"
                  // isDisabled={params.data.successful ? false : true}
                  color="default"
                  onPress={() => {
                    copyNo(params.value)
                  }}
                >
                  복사
                </Button>
                <span>{params.value}</span>
              </div>
            )
          }
        },
        cellRendererParams: {
          onPress: copyNo,
        },
      },
      {
        field: 'planTotCnt',
        headerName: lang('stuff.gridHeader.planTotCnt'),
        cellStyle: { textAlign: 'right' },
      },
      { field: 'objectName', headerName: lang('stuff.gridHeader.objectName'), cellStyle: { textAlign: 'left' } },
      {
        field: 'saleStoreId',
        headerName: lang('stuff.gridHeader.saleStoreId'),
        cellStyle: { textAlign: 'left' },
      },
      { field: 'saleStoreName', headerName: lang('stuff.gridHeader.saleStoreName'), cellStyle: { textAlign: 'left' } },
      { field: 'address', headerName: lang('stuff.gridHeader.address'), cellStyle: { textAlign: 'left' } },
      { field: 'dispCompanyName', headerName: lang('stuff.gridHeader.dispCompanyName'), cellStyle: { textAlign: 'left' } },
      { field: 'receiveUser', headerName: lang('stuff.gridHeader.receiveUser'), cellStyle: { textAlign: 'left' } },
      {
        field: 'specDate',
        headerName: lang('stuff.gridHeader.specDate'),
        valueFormatter: function (params) {
          if (params.value) {
            return dayjs(params?.value).format('YYYY.MM.DD')
          } else {
            return null
          }
        },
        cellStyle: { textAlign: 'center' },
      },
      {
        field: 'createDatetime',
        headerName: lang('stuff.gridHeader.createDatetime'),
        valueFormatter: function (params) {
          if (params.value) {
            return dayjs(params?.value).format('YYYY.MM.DD')
          } else {
            return null
          }
        },
        cellStyle: { textAlign: 'center' },
      },
    ],
    gridCount: 0,
  })

  //그리드 더블클릭
  const getCellDoubleClicked = (event) => {
    if (event.column.colId === 'objectNo') {
      return
    } else {
      console.log(' 상세이동::::::::', event.data)
      if (event.data.objectNo) {
        router.push(`${pathname}/detail?objectNo=${event.data.objectNo.toString()}`)
      } else {
        QToast({
          message: '물건정보가 없습니다',
          type: 'error',
        })
      }
    }
  }

  //그리드 체크박스 선택시
  const getSelectedRowdata = (data) => {
    // console.log('data:::', data)
    // let delData = data.map((row) => {
    //   return row.objectNo
    // })
    // console.log('delData::', delData)
    setSelectedRowData(data)
    setSelectedRowDataCount(data.length)
  }

  //물건삭제
  const fnDeleteRowData = (data) => {
    console.log('물건삭제:::::::::::')
    if (data.length === 0) {
      QToast({
        message: '삭제할 데이터를 선택하세요',
        type: 'error',
      })
      return false
    }
    let errCount = 0
    data.forEach((cell) => {
      if (!cell.objectNo) {
        // if (errCount === 0) {
        // QToast({
        //   message: `물건정보가 있는 행만 삭제 됩니다`,
        //   type: 'error',
        // })
        // }
        errCount++
      }
    })

    async function fetchDelete(data) {
      console.log('물건삭제API호출!!!!!!!!!', data)
      //행추가말고 api데이터만 보냄
      // let newData = data.filter((item) => item.company != null)
      // console.log('삭제에 전송되는 데이타::', newData)
      // await del({ url: '', data:newData })
      await get({ url: 'https://www.ag-grid.com/example-assets/space-mission-data.json' })
      // try {
      //   const res = await del({url:'', data:newData})

      //   if(!res || res.length === 0) {

      //   } else {
      fetchData()
      //   }
      // } catch (error) {
      //   console.error('Data Delete error:', error);
      // }
    }

    // 삭제API 완료 후 fetchData Api호출
    async function fetchData() {
      console.log('물건삭제후 조회API호출!!!!!!!!!!!!!', stuffSearchParams)
      const data = await get({ url: 'https://www.ag-grid.com/example-assets/space-mission-data.json' })
      setGridProps({ ...gridProps, gridData: data, count: data.length })
      setGridCount(data.length)
      //data.length = 10
      //setGridProps({ ...gridProps, gridData: data, count: data.length-1})
      //setGridCount(data.length - 1 )
    }

    if (errCount === 0) {
      // console.log('errCount::::::::', errCount)
      fetchDelete(data)
      // fetchData()
    } else {
      QToast({
        message: `물건정보가 있는 행만 선택해주세요`,
        type: 'error',
      })
    }
  }

  //행추가
  let newCount = 0
  const addRowItems = () => {
    // console.log('girdRef::::::', gridRef.current.api)
    const newItems = [
      {
        mission: newCount + 1,
        successful: true,
      },
    ]
    gridRef.current.api.applyTransaction({
      add: newItems,
      addIndex: newCount,
    })
    newCount++
  }

  //행삭제
  const removeRowItems = () => {
    // console.log('selectedRowData::', selectedRowData)
    let errCount = 0
    selectedRowData.forEach((cell) => {
      if (!cell.company) {
        let newSelectedRowData = selectedRowData.filter((item) => item.company == null)
        gridRef.current.api.applyTransaction({ remove: newSelectedRowData })
      } else {
        if (errCount === 0) {
          QToast({
            message: `행추가로 추가 한 행만 삭제됩니다.`,
            type: 'error',
          })
        }
        errCount++
      }
    })
  }

  // 진입시 그리드 데이터 조회
  useEffect(() => {
    if (stuffSearchParams?.code === 'S') {
      const params = {
        schObjectNo: '',
        schSaleStoreId: '',
        schAddress: '',
        schObjectName: '',
        schSaleStoreName: '',
        schSpecDateYn: '',
        schReceiveUser: '',
        schDispCompanyName: '',
        schDateType: 'U',
        schFromDt: dayjs(new Date()).add(-1, 'year').format('YYYY-MM-DD'),
        schToDt: dayjs(new Date()).format('YYYY-MM-DD'),
      }

      async function fetchData() {
        console.log('화면진입:::::::::::::', params)
        const apiUrl = `/api/object/v1.0/object?saleStoreId=201TES01&${queryStringFormatter(params)}`
        // console.log('apiUrl::', apiUrl)

        await get({
          url: apiUrl,
        }).then((res) => {
          if (res.length > 0) {
            console.log('API결과:::::::', res)
            setGridProps({ ...gridProps, gridData: res, count: res.length })
            setGridCount(res.length)
          }
        })
      }
      fetchData()
    }
  }, [])

  useEffect(() => {
    if (stuffSearchParams?.code === 'E') {
      console.log('조회 눌럿을때 ::::::::::::::', stuffSearchParams)
      async function fetchData() {
        const apiUrl = `/api/object/v1.0/object?saleStoreId=201TES01&${queryStringFormatter(stuffSearchParams)}`
        await get({ url: apiUrl }).then((res) => {
          console.log('API결과:::::::', res)
          setGridProps({ ...gridProps, gridData: res, count: res.length })
          setGridCount(res.length)
        })
      }
      fetchData()
    }
  }, [stuffSearchParams])

  return (
    <>
      <div className="text-2xl">
        물건목록
        <span>
          전체 : {gridCount} // 선택 : {selectedRowDataCount}
        </span>
        <div align="right">
          {/* <Button
            color="primary"
            onPress={() => {
              fnDeleteRowData(selectedRowData)
            }}
          >
            물건삭제
          </Button> */}
          {/* <Button
            color="primary"
            onPress={() => {
              addRowItems()
            }}
          >
            행추가
          </Button>
          <Button
            color="primary"
            onPress={() => {
              removeRowItems()
            }}
          >
            행삭제
          </Button> */}
        </div>
        <div style={{ width: '100%', height: '100%' }}>
          <StuffQGrid {...gridProps} getSelectedRowdata={getSelectedRowdata} getCellDoubleClicked={getCellDoubleClicked} gridRef={gridRef} />
        </div>
      </div>
    </>
  )
}
