'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 { useMessage } from '@/hooks/useMessage'
import StuffQGrid from './StuffQGrid'
import { useRecoilValue, useRecoilState } from 'recoil'
import { stuffSearchState } from '@/store/stuffAtom'
import { queryStringFormatter, isEmptyArray } 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 [stuffSearch, setStuffSearch] = useRecoilState(stuffSearchState)
  const { getMessage } = useMessage()
  const [curPage, setCurPage] = useState(1) //현재 페이지 번호
  const [defaultSize, setDefaultSize] = useState(100) //페이지 당 게시물 수
  const [defaultSortType, setDefaultSortType] = useState('R')
  const { get } = useAxios()
  const gridRef = useRef()

  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)
      alert('물건번호가 복사되었습니다.')
    } catch (error) {
      alert('물건번호 복사에 실패했습니다.')
    }
  }

  //물건번호 복사버튼 옆에 영역
  const onDoubleClick = (e) => {
    let objectNo = e.target.innerText
    console.log(objectNo)
    if (objectNo.substring(0, 1) === 'R') {
      console.log('진짜')
      router.push(`${pathname}/detail?objectNo=${objectNo.toString()}`)
    } else {
      console.log('임시')
      router.push(`${pathname}/tempdetail?objectNo=${objectNo.toString()}`)
    }
  }

  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: getMessage('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: getMessage('stuff.gridHeader.objectNo'),
        // headerClass: 'centered', //_test.scss에 추가 테스트
        cellRenderer: function (params) {
          if (params.data.objectNo) {
            return (
              <div>
                <Button
                  size="sm"
                  color="default"
                  onPress={() => {
                    copyNo(params.value)
                  }}
                >
                  복사
                </Button>
                <span onDoubleClick={onDoubleClick}>{params.value}</span>
              </div>
            )
          }
        },
        cellRendererParams: {
          onPress: copyNo,
        },
      },
      {
        field: 'planTotCnt',
        headerName: getMessage('stuff.gridHeader.planTotCnt'),
        cellStyle: { textAlign: 'right' },
      },
      { field: 'objectName', headerName: getMessage('stuff.gridHeader.objectName'), cellStyle: { textAlign: 'left' } },
      {
        field: 'saleStoreId',
        headerName: getMessage('stuff.gridHeader.saleStoreId'),
        cellStyle: { textAlign: 'left' },
      },
      { field: 'saleStoreName', headerName: getMessage('stuff.gridHeader.saleStoreName'), cellStyle: { textAlign: 'left' } },
      { field: 'address', headerName: getMessage('stuff.gridHeader.address'), cellStyle: { textAlign: 'left' } },
      { field: 'dispCompanyName', headerName: getMessage('stuff.gridHeader.dispCompanyName'), cellStyle: { textAlign: 'left' } },
      { field: 'receiveUser', headerName: getMessage('stuff.gridHeader.receiveUser'), cellStyle: { textAlign: 'left' } },
      {
        field: 'specDate',
        headerName: getMessage('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: getMessage('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)
      //T 면 임시 R은 진짜
      if (event.data.objectNo) {
        if (event.data.objectNo.substring(0, 1) === 'R') {
          console.log('진짜:::::::::')
          router.push(`${pathname}/detail?objectNo=${event.data.objectNo.toString()}`)
        } else {
          console.log('임시:::::::::::::::::')
          router.push(`${pathname}/tempdetail?objectNo=${event.data.objectNo.toString()}`)
        }
      }
    }
  }

  //그리드 체크박스 선택시
  const getSelectedRowdata = (data) => {
    setSelectedRowData(data)
    setSelectedRowDataCount(data.length)
  }

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

  //행추가
  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) {
          alert('행추가로 추가 한 행만 삭제됩니다.')
        }
        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'),
        startRow: (curPage - 1) * defaultSize + 1,
        endRow: curPage * defaultSize,
        schSelSaleStoreId: '',
        schSortType: 'R',
      }

      async function fetchData() {
        console.log('화면진입:::::::::::::', params)
        //api에 넘길값 startRow, endRow
        // let startRow
        // let endRow
        // startRow = (curPage - 1) * size + 1
        // endRow = curPage * size
        // console.log('startrow::', startRow)
        // console.log('endRow::', endRow)

        // let curPage
        // let totalpage
        // let totalCount
        // let size
        // let pageCount

        const apiUrl = `/api/object/list?saleStoreId=201TES01&${queryStringFormatter(params)}`

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

  useEffect(() => {
    if (stuffSearchParams?.code === 'E') {
      stuffSearchParams.startRow = (curPage - 1) * defaultSize + 1
      stuffSearchParams.endRow = curPage * defaultSize
      stuffSearchParams.schSortType = defaultSortType
      console.log('조회 눌럿을때 ::::::::::::::', stuffSearchParams)
      async function fetchData() {
        const apiUrl = `/api/object/list?saleStoreId=201TES01&${queryStringFormatter(stuffSearchParams)}`
        await get({ url: apiUrl }).then((res) => {
          console.log('API결과:::::::', res)
          if (!isEmptyArray(res)) {
            setGridProps({ ...gridProps, gridData: res, count: res.length })
            setGridCount(res.length)
          } else {
            setGridProps({ ...gridProps, gridData: [], count: 0 })
            setGridCount(0)
          }
        })
      }
      fetchData()
    }
  }, [stuffSearchParams])

  //페이지 갯수 변경 이벤트
  const onChangePerPage = (e) => {
    let startRow = (curPage - 1) * e.target.value + 1
    stuffSearchParams.startRow = startRow
    stuffSearchParams.endRow = curPage * e.target.value
    setDefaultSize(e.target.value)
    setStuffSearch({
      ...stuffSearch,
      code: 'S',
      startRow: startRow,
      endRow: curPage * e.target.value,
    })
    console.log('셋팅된 검색조건:::', stuffSearchParams)
    //조회API호출
    const apiUrl = `/api/object/list?saleStoreId=201TES01&${queryStringFormatter(stuffSearchParams)}`
    get({ url: apiUrl }).then((res) => {
      console.log('보여줄개수바꿨을때 조회 ::::::::::', res)
      if (!isEmptyArray(res)) {
        setGridProps({ ...gridProps, gridData: res, count: res.length })
        setGridCount(res.length)
      } else {
        setGridProps({ ...gridProps, gridData: [], count: 0 })
        setGridCount(0)
      }
    })
  }

  //최근 등록일 수정일 정렬 이벤트
  const onChangeSortType = (e) => {
    stuffSearchParams.schSortType = e.target.value
    console.log('셋팅된 검색조건:::', stuffSearchParams)
    setDefaultSortType(e.target.value)
    setStuffSearch({
      ...stuffSearch,
      code: 'S',
      schSortType: e.target.value,
    })
    const apiUrl = `/api/object/list?saleStoreId=201TES01&${queryStringFormatter(stuffSearchParams)}`
    // console.log('apiUrl::', apiUrl)
    get({ url: apiUrl }).then((res) => {
      console.log('정렬바꿨을때 조회 ::::::::::', res)
      if (!isEmptyArray(res)) {
        setGridProps({ ...gridProps, gridData: res, count: res.length })
        setGridCount(res.length)
      } else {
        setGridProps({ ...gridProps, gridData: [], count: 0 })
        setGridCount(0)
      }
    })
  }
  return (
    <>
      <div className="text-2xl">
        물건목록
        <span>
          전체 : {gridCount} // 선택 : {selectedRowDataCount}
        </span>
        <select className="select" onChange={onChangePerPage}>
          <option value="100">100</option>
          <option value="200">200</option>
          <option value="300">300</option>
        </select>
        <select className="select" onChange={onChangeSortType}>
          <option value="R">최근 등록일</option>
          <option value="U">최근 수정일</option>
        </select>
        <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>
    </>
  )
}
