import type { Plugin } from '@/app/components/plugins/types'
import {
  RiArrowDownSLine,
  RiArrowRightUpLine,
} from '@remixicon/react'
import { useTheme } from 'next-themes'
import Link from 'next/link'
import {
  memo,
  useCallback,
  useState,
} from 'react'
import { useTranslation } from 'react-i18next'
import Divider from '@/app/components/base/divider'
import Loading from '@/app/components/base/loading'
import List from '@/app/components/plugins/marketplace/list'
import ProviderCard from '@/app/components/plugins/provider-card'
import { cn } from '@/utils/classnames'
import { getMarketplaceUrl } from '@/utils/var'
import {
  useMarketplaceAllPlugins,
} from './hooks'

type InstallFromMarketplaceProps = {
  providers: any[]
  searchText: string
}
const InstallFromMarketplace = ({
  providers,
  searchText,
}: InstallFromMarketplaceProps) => {
  const { t } = useTranslation()
  const { theme } = useTheme()
  const [collapse, setCollapse] = useState(false)
  const {
    plugins: allPlugins,
    isLoading: isAllPluginsLoading,
  } = useMarketplaceAllPlugins(providers, searchText)

  const cardRender = useCallback((plugin: Plugin) => {
    if (plugin.type === 'bundle')
      return null

    return <ProviderCard key={plugin.plugin_id} payload={plugin} />
  }, [])

  return (
    <div className="mb-2">
      <Divider className="!mt-4 h-px" />
      <div className="flex items-center justify-between">
        <div className="system-md-semibold flex cursor-pointer items-center gap-1 text-text-primary" onClick={() => setCollapse(!collapse)}>
          <RiArrowDownSLine className={cn('h-4 w-4', collapse && '-rotate-90')} />
          {t('modelProvider.installDataSourceProvider', { ns: 'common' })}
        </div>
        <div className="mb-2 flex items-center pt-2">
          <span className="system-sm-regular pr-1 text-text-tertiary">{t('modelProvider.discoverMore', { ns: 'common' })}</span>
          <Link target="_blank" href={getMarketplaceUrl('', { theme })} className="system-sm-medium inline-flex items-center text-text-accent">
            {t('marketplace.difyMarketplace', { ns: 'plugin' })}
            <RiArrowRightUpLine className="h-4 w-4" />
          </Link>
        </div>
      </div>
      {!collapse && isAllPluginsLoading && <Loading type="area" />}
      {
        !isAllPluginsLoading && !collapse && (
          <List
            marketplaceCollections={[]}
            marketplaceCollectionPluginsMap={{}}
            plugins={allPlugins}
            showInstallButton
            cardContainerClassName="grid grid-cols-2 gap-2"
            cardRender={cardRender}
            emptyClassName="h-auto"
          />
        )
      }
    </div>
  )
}

export default memo(InstallFromMarketplace)
