import { defineComponent } from 'vue'
import useSearchStore from './useSearchStore'
import jump from '@/utils/jump'
import useSearchConfigStore from './useSearchConfigStore'
import { OhVueIcon, addIcons } from 'oh-vue-icons'
import { MdSearch } from 'oh-vue-icons/icons'
import { aIUrl, translateUrl } from '@/config'

addIcons(MdSearch)

export const Item = defineComponent({
  props: {
    icon: { type: Object, default: null },
    label: { type: String, default: '' },
    path: { type: String, default: '' },
    prefix: { type: String, default: '' },
    num: { type: Number, default: 0 },
    current: { type: Number, default: -1 }
  },
  setup(props) {
    const searchConfig = useSearchConfigStore()
    const search = useSearchStore()
    return () => (
      <div
        class={
          'flex justify-between items-center text-black/80 cursor-pointer  py-1 px-2 rounded transition-all ' +
          (props.current === props.num ? 'bg-white/40' : 'hover:bg-white/40')
        }
        onClick={() => {
          searchConfig.addHistory(props.path)
          search.searchStr = ''
          jump(props.prefix + props.path)
        }}
      >
        <span>{props.icon}</span>
        <div class="w-0 pl-2 flex-grow overflow-hidden text-ellipsis break-all whitespace-nowrap">
          {props.label + props.path}
        </div>
      </div>
    )
  }
})

export default defineComponent(() => {
  const search = useSearchStore()
  const searchConfig = useSearchConfigStore()

  return () => (
    <div class="absolute left-0 -bottom-2 translate-y-full w-full rounded-lg bg-white/60 backdrop-blur shadow-lg p-4">
      <Item
        prefix={aIUrl}
        path={search.searchStr}
        label="AI搜索："
        icon={<img class="w-4 h-4" src="/tab/searchIcons/mita.jpg" alt="mita" />}
        current={search.current}
        num={0}
      />
      <Item
        prefix={translateUrl}
        path={search.searchStr}
        label="AI翻译："
        icon={<img class="w-4 h-4" src="/tab/searchIcons/translate.png" alt="translate" />}
        current={search.current}
        num={1}
      />
      {search.sugList.map((el, idx) => (
        <Item
          key={idx}
          prefix={searchConfig.current.url}
          path={el}
          icon={<OhVueIcon name="md-search" />}
          current={search.current}
          num={idx + 2}
        />
      ))}
    </div>
  )
})
