import { useState } from 'react';
import { useResources } from '../hooks/useApi';
import { CustomCard } from '../components/CustomCard';
import { Hero } from '../components/Hero';
import { Button, Link, Chip } from '@heroui/react';
import { buttonVariants, linkVariants } 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<any>(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="text-3xl font-bold text-center mb-12">传送门</h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            {PORTALS.map((portal) => {
              const isExternal = portal.url.startsWith('http');
              const Content = (
                <CustomCard className="group cursor-pointer p-6 h-full">
                  <div className="flex gap-4">
                    <div className="p-3 rounded-2xl bg-default-100 text-default-600 group-hover:bg-primary-50 group-hover:text-primary transition-colors">
                      <portal.icon className="w-6 h-6" />
                    </div>
                    <div className="flex flex-col gap-1">
                      <h3 className="text-lg font-bold">{portal.title}</h3>
                      <p className="text-sm text-default-500 line-clamp-1">{portal.description}</p>
                    </div>
                  </div>
                </CustomCard>
              );

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

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

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