import { useState } from 'react'
import { useResources, Resource } from '../hooks/useApi'
import { CustomCard } from '../components/CustomCard'
import { Hero } from '../components/Hero'
import { Button, Chip } from '@heroui/react'
import { buttonVariants } from '@heroui/styles'
import { CreateResourceModal } from '../components/CreateResourceModal'
import { EditResourceModal } from '../components/EditResourceModal'
import { useSession } from '../lib/auth-client'
import {
  ChatBubbleLeftEllipsisIcon,
  BookOpenIcon,
  BookmarkIcon,
  QuestionMarkCircleIcon,
  WrenchScrewdriverIcon,
  ListBulletIcon,
  VideoCameraIcon,
  UserGroupIcon,
} from '@heroicons/react/24/outline'
import { Link as RouterLink } from 'react-router-dom'

const PORTALS = [
  {
    title: '中文论坛',
    description: 'HLAE中文交流社区',
    icon: ChatBubbleLeftEllipsisIcon,
    url: 'https://bbs.hlae.site',
  },
  {
    title: '官方Wiki',
    description: '权威，但是英文 orz',
    icon: BookOpenIcon,
    url: 'https://github.com/advancedfx/advancedfx/wiki',
  },
  {
    title: '新版文档',
    description: '新版 advancedfx 文档，建设中',
    icon: BookmarkIcon,
    url: 'https://docs.hlae.site',
  },
  {
    title: '官方Discord',
    description: '和开发者近距离交流',
    icon: UserGroupIcon,
    url: 'https://discord.gg/advancedfx',
  },
  {
    title: '问题与建议提交',
    description: 'tnnd 为什么不更新',
    icon: QuestionMarkCircleIcon,
    url: 'https://github.com/advancedfx/advancedfx/issues',
  },
  {
    title: 'HUD生成器',
    description: '击杀信息和准星生成工具',
    icon: WrenchScrewdriverIcon,
    url: '/hud-generator',
  },
  {
    title: '击杀信息生成',
    description: 'CS2 · CS 击杀信息生成工具（测试）',
    icon: ListBulletIcon,
    url: '/demo',
  },
  {
    title: 'HLTV',
    description: 'CSGO新闻、数据、录像',
    icon: VideoCameraIcon,
    url: 'https://www.hltv.org',
  },
]

export default function HomePage() {
  const { resources, isLoading } = useResources()
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isEditModalOpen, setIsEditModalOpen] = useState(false)
  const [selectedResource, setSelectedResource] = useState<Resource | null>(
    null,
  )
  const { data: session } = useSession()

  return (
    <div className="pb-20">
      <main className="container mx-auto px-6">
        <Hero />
        {/* Portals Section */}
        <section className="mb-20">
          <h2 className="mb-12 text-center text-3xl font-bold">传送门</h2>
          <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
            {PORTALS.map((portal) => {
              const isExternal = portal.url.startsWith('http')
              const Content = (
                <CustomCard className="group h-full cursor-pointer p-6">
                  <div className="flex gap-4">
                    <div className="bg-default-100 text-default-600 group-hover:bg-primary-50 group-hover:text-primary rounded-2xl p-3 transition-colors">
                      <portal.icon className="h-6 w-6" />
                    </div>
                    <div className="flex flex-col gap-1">
                      <h3 className="text-lg font-bold">{portal.title}</h3>
                      <p className="text-default-500 line-clamp-1 text-sm">
                        {portal.description}
                      </p>
                    </div>
                  </div>
                </CustomCard>
              )

              return isExternal ? (
                <a
                  key={portal.title}
                  href={portal.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="block text-inherit no-underline"
                >
                  {Content}
                </a>
              ) : (
                <RouterLink
                  key={portal.title}
                  to={portal.url}
                  className="block text-inherit no-underline"
                >
                  {Content}
                </RouterLink>
              )
            })}
          </div>
        </section>

        {/* Resources Section */}
        <section>
          <div className="relative mb-12 flex items-center justify-center">
            <h2 className="text-3xl font-bold">资源下载</h2>
            {session && (
              <Button
                onPress={() => setIsModalOpen(true)}
                variant="tertiary"
                className="absolute right-0"
              >
                添加资源
              </Button>
            )}
          </div>

          <CreateResourceModal
            isOpen={isModalOpen}
            onOpenChange={setIsModalOpen}
          />
          <EditResourceModal
            isOpen={isEditModalOpen}
            onOpenChange={setIsEditModalOpen}
            resource={selectedResource}
          />

          {isLoading ? (
            <div className="flex justify-center py-20">加载中...</div>
          ) : (
            <div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
              {resources?.map((res) => (
                <CustomCard key={res.id} className="p-6">
                  <div className="mb-4 flex gap-4">
                    <div className="bg-default-100 flex h-16 w-16 flex-shrink-0 items-center justify-center overflow-hidden rounded-2xl">
                      {res.icon ? (
                        <img
                          alt={res.title}
                          src={res.icon}
                          className="h-10 w-10 object-contain"
                        />
                      ) : (
                        <div className="text-default-400 text-2xl font-bold">
                          {res.title[0]}
                        </div>
                      )}
                    </div>
                    <div className="flex min-w-0 flex-1 flex-col gap-1">
                      <div className="flex items-center gap-2">
                        <h3 className="truncate text-lg font-bold">
                          {res.title}
                        </h3>
                        {res.category && (
                          <Chip
                            size="sm"
                            variant="soft"
                            className="h-5 text-[10px]"
                          >
                            {res.category}
                          </Chip>
                        )}
                      </div>
                      <p className="text-default-500 line-clamp-2 text-sm">
                        {res.description}
                      </p>
                    </div>
                  </div>

                  <div className="mt-auto flex gap-3">
                    <a
                      href={res.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className={buttonVariants({
                        fullWidth: true,
                        className:
                          'flex h-10 items-center justify-center rounded-3xl bg-[#C14B4B] px-4 font-medium text-white hover:opacity-90',
                      })}
                    >
                      加速下载
                    </a>
                    <a
                      href={res.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className={buttonVariants({
                        fullWidth: true,
                        variant: 'tertiary',
                        className:
                          'bg-default-200 text-default-600 hover:bg-default-300 flex h-10 items-center justify-center rounded-3xl px-4 font-medium',
                      })}
                    >
                      原始下载
                    </a>
                    {session && (
                      <Button
                        isIconOnly
                        variant="secondary"
                        onPress={() => {
                          setSelectedResource(res)
                          setIsEditModalOpen(true)
                        }}
                        className="flex-shrink-0"
                      >
                        <WrenchScrewdriverIcon className="h-4 w-4" />
                      </Button>
                    )}
                  </div>
                </CustomCard>
              ))}
              {!resources?.length && (
                <div className="text-default-400 col-span-full py-20 text-center">
                  暂无资源
                </div>
              )}
            </div>
          )}
        </section>
      </main>
    </div>
  )
}
