import { useState } from 'react'
import { Resource, usePortals } from '../hooks/useApi'
import { Hero } from '../components/Hero'
import { Button } from '@heroui/react'
import { CreateResourceModal } from '../components/CreateResourceModal'
import { EditResourceModal } from '../components/EditResourceModal'
import { useSession } from '../lib/auth-client'
import { Card } from '../components/Card'
import { ResourceCardList } from '../components/ResourceCardList'

export default function HomePage() {
  const { portals, isLoading: isPortalsLoading } = usePortals()
  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>
          {isPortalsLoading ? (
            <div className="py-20 text-center">加载中...</div>
          ) : (
            <ul className="grid w-full grid-cols-1 items-center justify-center gap-6 sm:grid-cols-2 lg:grid-cols-3">
              {portals?.map((portal) => (
                <Card
                  key={portal.id}
                  title={portal.title}
                  url={portal.url}
                  description={portal.description}
                  icon={portal.icon}
                  background={portal.background}
                />
              ))}
            </ul>
          )}
        </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="flat"
                className="absolute right-0"
              >
                添加资源
              </Button>
            )}
          </div>

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

          <ResourceCardList
            onEdit={(resource) => {
              setSelectedResource(resource)
              setIsEditModalOpen(true)
            }}
          />
        </section>
      </main>
    </div>
  )
}
