import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { memo, useState } from 'react'
import { ExternalLink, Store, Globe } from 'lucide-react'

const storeList = [
  {
    name: 'modelscope.cn',
    link: 'https://www.modelscope.cn/mcp',
  },
  {
    name: 'mcpmarket.cn',
    link: 'https://mcpmarket.cn',
  },
  {
    name: 'mcp.so',
    link: 'https://mcp.so',
  },
]

export const McpStorePopover = memo(() => {
  const [menuOpen, setMenuOpen] = useState(false)

  return (
    <Popover open={menuOpen} onOpenChange={setMenuOpen}>
      <TooltipProvider>
        <Tooltip>
          <TooltipTrigger asChild>
            <PopoverTrigger asChild>
              <button className="inline-flex items-center justify-center rounded-full w-7 h-7 bg-gray-100 text-gray-900 transition-colors hover:bg-gray-200">
                <Store className="h-3.5 w-3.5" />
              </button>
            </PopoverTrigger>
          </TooltipTrigger>
          <TooltipContent>
            <p>MCP 市场</p>
          </TooltipContent>
        </Tooltip>
      </TooltipProvider>
      <PopoverContent align="start" className="w-60 border border-border bg-popover p-1">
        <div className="px-3 py-2 text-sm font-medium text-foreground">
          MCP 市场
        </div>
        <div className="flex flex-col gap-1 mt-1">
          {storeList.map((item) => (
            <button
              type="button"
              key={item.name}
              className="group flex cursor-pointer items-center justify-between rounded-lg px-3 py-3 transition-colors hover:bg-accent"
              onClick={() => {
                setMenuOpen(false)
                if (typeof window !== 'undefined') {
                  window.open(item.link, '_blank')
                }
              }}
            >
              <div className="flex items-center gap-1.5">
                <Globe className="h-4 w-4 text-muted-foreground" />
                <div className="text-sm text-foreground">{item.name}</div>
              </div>
              <ExternalLink className="h-4 w-4 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
            </button>
          ))}
        </div>
      </PopoverContent>
    </Popover>
  )
})
