import { useEffect, useState } from 'react'
import { Button, Dropdown, Input, Layout, List, Space, Typography } from '@arco-design/web-react'
import { IconMoon, IconSearch, IconSun } from '@arco-design/web-react/icon'
import type { SearchResultDTO } from '../../api/search'
import type { Theme } from './project-types'

const { Header } = Layout
const { Text } = Typography

export function ProjectTopbar({
  theme,
  onToggleTheme,
  query,
  loading,
  searched,
  results,
  onQueryChange,
  onSearch,
  onSelectSearchResult,
}: {
  theme: Theme
  onToggleTheme: () => void
  query: string
  loading: boolean
  searched: boolean
  results: SearchResultDTO[]
  onQueryChange: (value: string) => void
  onSearch: () => void
  onSelectSearchResult: (result: SearchResultDTO) => void
}) {
  const [popupVisible, setPopupVisible] = useState(false)

  useEffect(() => {
    if (!loading && searched) setPopupVisible(true)
  }, [loading, results, searched])

  const submitSearch = () => {
    setPopupVisible(false)
    onSearch()
  }

  const searchResults = (
    <div className="search-results-dropdown" aria-label="搜索结果">
      <List<SearchResultDTO>
        size="small"
        bordered={false}
        dataSource={results}
        noDataElement="未找到匹配结果"
        render={(result) => (
          <List.Item key={`${result.type}:${result.id}`}>
            <button
              type="button"
              className="search-result-item"
              onClick={() => {
                setPopupVisible(false)
                onSelectSearchResult(result)
              }}
            >
              <span className="search-result-heading">
                <Text>{result.title}</Text>
                <Text className="search-result-type" type="secondary">{searchTypeLabel(result.type)}</Text>
              </span>
              {result.snippet && <Text className="search-result-snippet" type="secondary">{result.snippet}</Text>}
            </button>
          </List.Item>
        )}
      />
    </div>
  )

  return (
    <Header className="topbar">
      <div className="brand-lockup">
        <img className="brand-icon" src="/senlinai-icon.svg" alt="" />
        <Text className="brand-name">森林AI</Text>
      </div>
      <Dropdown
        droplist={searchResults}
        popupVisible={popupVisible && searched}
        trigger="click"
        position="bl"
        onVisibleChange={(visible) => setPopupVisible(visible && searched)}
      >
        <div className="global-search" role="search">
          <Input
            size="large"
            prefix={<IconSearch />}
            placeholder="搜索项目、任务和笔记"
            value={query}
            onChange={(value) => {
              setPopupVisible(false)
              onQueryChange(value)
            }}
            onPressEnter={submitSearch}
          />
          <Button size="large" type="primary" loading={loading} onClick={submitSearch}>搜索</Button>
        </div>
      </Dropdown>
      <Space className="topbar-actions">
        <Button aria-label={theme === 'dark' ? '切换浅色模式' : '切换深色模式'} icon={theme === 'dark' ? <IconSun /> : <IconMoon />} onClick={onToggleTheme} />
      </Space>
    </Header>
  )
}

function searchTypeLabel(type: string) {
  if (type === 'project') return '项目'
  if (type === 'task') return '任务'
  if (type === 'note') return '笔记'
  return '未知'
}
