'use client'

import { useSuitableStore } from '@/store/useSuitableStore'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useRouter } from 'next/navigation'
import type { Suitable as SuitableType } from '@/api/suitable'

export default function Suitable() {
  const router = useRouter()
  const queryClient = useQueryClient()
  const { selectedItems, addSelectedItem, removeSelectedItem } = useSuitableStore()

  const handleItemClick = (item: SuitableType) => {
    if (!item.id) return // 초기 데이터 import 때문에 Suitable.id가 optional 타입이라서 방어 처리 추가
    selectedItems.some((selected) => selected.id === item.id) ? removeSelectedItem(item.id) : addSelectedItem(item)
  }

  const { data: suitableList, isLoading } = useQuery<SuitableType[]>({
    queryKey: ['suitables', 'search'],
    queryFn: async () => {
      const data = queryClient.getQueryData(['suitables', 'search']) as SuitableType[]
      return data ?? []
    },
    enabled: false,
  })

  if (isLoading || !suitableList || suitableList.length === 0) {
    return <div>Loading...</div>
  }

  return (
    <>
      <h1 className="text-4xl font-bold">Suitable</h1>
      <button
        className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
        onClick={() => {
          router.push('/')
        }}
      >
        HOME
      </button>
      <div>
        <h2 className="text-lg font-semibold mb-2">선택된 아이템</h2>
        {selectedItems.length > 0 ? (
          selectedItems.map((item) => (
            <div key={item.id} onClick={() => handleItemClick(item)}>
              {item.product_name}
            </div>
          ))
        ) : (
          <div>선택된 아이템이 없습니다.</div>
        )}
      </div>
      <br />
      <div>
        <h2 className="text-lg font-semibold mb-2">데이터 목록</h2>
        {suitableList ? (
          suitableList.map((item: SuitableType) => (
            <div key={item.id} className="p-2 border rounded cursor-pointer hover:bg-gray-100" onClick={() => handleItemClick(item)}>
              {item.product_name}
            </div>
          ))
        ) : (
          <div>검색 결과가 없습니다.</div>
        )}
      </div>
    </>
  )
}
