import useSWR from 'swr'
import { Card, CardProps } from './Card'
import { useResources, Resource } from '../hooks/useApi'
import { fetchResourceReleaseData, LatestRelease } from '../lib/github'
import { useSession } from '../lib/auth-client'
import { Button } from '@heroui/react'
import { WrenchScrewdriverIcon } from '@heroicons/react/24/outline'

interface ResourceCardListProps {
  onEdit?: (resource: Resource) => void
}

export function ResourceCardList({ onEdit }: ResourceCardListProps) {
  const { resources, isLoading } = useResources()
  const { data: session } = useSession()

  const repos =
    resources
      ?.map((item) => item.githubRepo)
      .filter((repo): repo is string => !!repo && repo.includes('/')) || []

  const { data: releaseData } = useSWR(
    repos.length > 0 ? ['resource-releases', repos] : null,
    ([, repos]) => fetchResourceReleaseData(repos),
    {
      revalidateOnFocus: false,
      dedupingInterval: 180000, // 3 mins
    },
  )

  const repoReleaseMap = new Map<string, LatestRelease>()
  if (releaseData) {
    releaseData.results.forEach((result) => {
      if (result.success && result.latest_release) {
        repoReleaseMap.set(result.repo, result.latest_release)
      }
    })
  }

  if (isLoading) {
    return <div className="py-20 text-center">加载中...</div>
  }

  if (!resources?.length) {
    return <div className="col-span-full py-20 text-center text-default-400">暂无资源</div>
  }

  return (
    <ul className="grid w-full grid-cols-1 items-center justify-center gap-6 sm:grid-cols-2 lg:grid-cols-3">
      {resources.map((item) => {
        const releaseInfo = item.githubRepo
          ? repoReleaseMap.get(item.githubRepo)
          : undefined

        const cardProps: CardProps = {
          title: item.title,
          url: item.url,
          description: item.description,
          icon: item.icon,
          background: item.background,
          githubRepo: item.githubRepo,
          downloadCdn: item.downloadCdn,
          downloadOriginal: item.downloadOriginal,
          image: item.image,
          version: releaseInfo?.latest_version || item.version,
          onVersionClick: releaseInfo
            ? (e) => {
                e.preventDefault()
                window.open(
                  `https://github.com/${item.githubRepo}/releases/tag/${releaseInfo.latest_version}`,
                  '_blank',
                )
              }
            : undefined,
          action:
            session && onEdit ? (
              <Button
                isIconOnly
                variant="flat"
                size="sm"
                onPress={() => onEdit(item)}
                className="absolute right-2 top-2 z-10 opacity-0 transition-opacity group-hover:opacity-100"
              >
                <WrenchScrewdriverIcon className="h-4 w-4" />
              </Button>
            ) : undefined,
        }

        return <Card {...cardProps} key={item.id} />
      })}
    </ul>
  )
}
