'use client'
import { useInquiryFilterStore } from '@/store/inquiryFilterStore'
import { useRouter, useSearchParams } from 'next/navigation'
import { useEffect, useState } from 'react'
import { useAlertMsg, WARNING_MESSAGE } from '@/hooks/useAlertMsg'

export default function ListForm() {
  const router = useRouter()
  const { inquiryListRequest, setInquiryListRequest, setOffset } = useInquiryFilterStore()
  const { showErrorAlert } = useAlertMsg()
  const [searchKeyword, setSearchKeyword] = useState(inquiryListRequest.schTitle ?? '')
  const searchParams = useSearchParams()

  useEffect(() => {
    if (searchParams.get('isMyInquiry') === 'false') {
      setSearchKeyword('')
      setInquiryListRequest({ ...inquiryListRequest, schTitle: null })
    }
  }, [searchParams])

  const handleSearch = () => {
    if (searchKeyword.length >= 2) {
      setInquiryListRequest({ ...inquiryListRequest, schTitle: searchKeyword })
    } else {
      showErrorAlert(WARNING_MESSAGE.KEYWORD_MINIMUM_LENGTH)
    }
  }
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleSearch()
    }
  }

  return (
    <>
      <div className="sale-frame">
        <div className="sale-form-bx">
          <button className="btn-frame n-blue icon" onClick={() => router.push('/inquiry/regist')}>
            お問い合わせ<i className="btn-arr"></i>
          </button>
        </div>
        <div className="sale-form-bx">
          <div className="search-input">
            <input
              type="text"
              className="search-frame"
              placeholder="タイトルを入力してください. (2文字以上)"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              onKeyDown={handleKeyDown}
            />
            {searchKeyword && (
              <button
                className="del-icon"
                onClick={() => {
                  setSearchKeyword('')
                  setInquiryListRequest({
                    ...inquiryListRequest,
                    schTitle: '',
                  })
                  setOffset(1)
                }}
              ></button>
            )}
            <button className="search-icon" onClick={handleSearch}></button>
          </div>
        </div>
      </div>
    </>
  )
}
