"use client"

import type React from "react"

import { AdminNav } from "@/components/admin-nav"
import { ThemeToggle } from "@/components/theme-toggle"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { useToast } from "@/components/ui/use-toast"
import { useAuth } from "@/context/auth-context"
import { BookOpen, Edit, Eye, Plus, Search, Trash2 } from "lucide-react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { useEffect, useState } from "react"
import { fetchWithAuth } from "@/lib/api"

interface Book {
  bookId: number
  title: string
  isbn: string
  price: number
  stock: number
  publishDate: string
  publisherName: string
  description: string
  coverImage: string
  author: string[]
}

interface BooksResponse {
  pageNum: number
  pageSize: number
  total: number
  data: Book[]
}

export default function AdminBooksPage() {
  const { user } = useAuth()
  const router = useRouter()
  const { toast } = useToast()
  const [books, setBooks] = useState<BooksResponse | null>(null)
  const [loading, setLoading] = useState(true)
  const [currentPage, setCurrentPage] = useState(1)
  const [searchTerm, setSearchTerm] = useState("")

  useEffect(() => {
    // 检查用户是否登录且是管理员
    if (!user) {
      toast({
        title: "请先登录",
        description: "您需要登录后才能访问管理页面",
        variant: "destructive",
      })
      router.push("/login")
      return
    }

    if (!user.isAdmin) {
      toast({
        title: "权限不足",
        description: "您没有管理员权限",
        variant: "destructive",
      })
      router.push("/")
      return
    }

    const fetchBooks = async () => {
      setLoading(true)
      try {
        let url = `book/all?pageNum=${currentPage}&pageSize=10`

        if (searchTerm) {
          url = `book/search/title?title=${encodeURIComponent(searchTerm)}&pageNum=${currentPage}&pageSize=10`
        }

        const response = await fetchWithAuth(url)
        const result = await response.json()

        if (result.code === 0) {
          setBooks(result.data)
        } else {
          toast({
            variant: "destructive",
            title: "获取图书失败",
            description: result.msg || "无法获取图书信息",
          })
        }
      } catch (error) {
        toast({
          variant: "destructive",
          title: "获取图书失败",
          description: "服务器连接错误，请稍后再试",
        })
      } finally {
        setLoading(false)
      }
    }

    fetchBooks()
  }, [user, router, toast, currentPage, searchTerm])

  const handlePageChange = (page: number) => {
    setCurrentPage(page)
  }

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault()
    setCurrentPage(1)
  }

  const handleDeleteBook = async (bookId: number) => {
    if (confirm("确定要删除这本图书吗？此操作不可撤销。")) {
      try {
        const response = await fetchWithAuth(`book/admin/delete/${bookId}`, {
          method: "DELETE",
        })

        const result = await response.json()

        if (result.code === 0) {
          toast({
            title: "删除成功",
            description: "图书已成功删除",
          })

          // 刷新图书列表
          if (books && books.data.length === 1 && currentPage > 1) {
            setCurrentPage(currentPage - 1)
          } else {
            // 保持在当前页，但刷新数据
            const updatedBooks = { ...books } as BooksResponse
            updatedBooks.data = updatedBooks.data.filter((book) => book.bookId !== bookId)
            updatedBooks.total -= 1
            setBooks(updatedBooks)
          }
        } else {
          toast({
            variant: "destructive",
            title: "删除失败",
            description: result.msg || "无法删除图书",
          })
        }
      } catch (error) {
        toast({
          variant: "destructive",
          title: "删除失败",
          description: "服务器连接错误，请稍后再试",
        })
      }
    }
  }

  if (!user || !user.isAdmin) {
    return null
  }

  return (
    <div className="flex min-h-screen flex-col">
      <header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
        <div className="container flex h-16 items-center justify-between">
          <div className="flex items-center gap-2 font-semibold">
            <BookOpen className="h-6 w-6" />
            <span>图书管理系统 - 管理后台</span>
          </div>
          <div className="flex items-center gap-4">
            <ThemeToggle />
            <Button variant="ghost" onClick={() => router.push("/")}>
              返回前台
            </Button>
          </div>
        </div>
      </header>
      <div className="flex flex-1">
        <AdminNav />
        <main className="flex-1 p-6">
          <div className="space-y-6">
            <div className="flex justify-between items-center">
              <h1 className="text-3xl font-bold">图书管理</h1>
              <Link href="/admin/books/add">
                <Button>
                  <Plus className="mr-2 h-4 w-4" />
                  添加图书
                </Button>
              </Link>
            </div>

            <Card>
              <CardHeader>
                <CardTitle>图书列表</CardTitle>
              </CardHeader>
              <CardContent>
                <form onSubmit={handleSearch} className="flex w-full max-w-sm items-center space-x-2 mb-6">
                  <Input
                    type="search"
                    placeholder="搜索图书标题..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                  />
                  <Button type="submit">
                    <Search className="h-4 w-4" />
                  </Button>
                </form>

                {loading ? (
                  <div className="flex justify-center items-center h-[400px]">
                    <div className="animate-pulse text-xl">加载中...</div>
                  </div>
                ) : !books || books.data.length === 0 ? (
                  <div className="flex flex-col items-center justify-center py-12">
                    <BookOpen className="h-12 w-12 text-muted-foreground mb-4" />
                    <h2 className="text-xl font-semibold">没有找到图书</h2>
                    <p className="text-muted-foreground mt-2">
                      {searchTerm ? "尝试使用不同的搜索词" : "添加一些图书开始管理"}
                    </p>
                    {!searchTerm && (
                      <Link href="/admin/books/add">
                        <Button className="mt-4">
                          <Plus className="mr-2 h-4 w-4" />
                          添加图书
                        </Button>
                      </Link>
                    )}
                  </div>
                ) : (
                  <>
                    <div className="rounded-md border">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>ID</TableHead>
                            <TableHead>标题</TableHead>
                            <TableHead>ISBN</TableHead>
                            <TableHead>价格</TableHead>
                            <TableHead>库存</TableHead>
                            <TableHead>出版社</TableHead>
                            <TableHead>操作</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {books.data.map((book) => (
                            <TableRow key={book.bookId}>
                              <TableCell>{book.bookId}</TableCell>
                              <TableCell className="font-medium">{book.title}</TableCell>
                              <TableCell>{book.isbn}</TableCell>
                              <TableCell>¥{book.price.toFixed(2)}</TableCell>
                              <TableCell>{book.stock}</TableCell>
                              <TableCell>{book.publisherName}</TableCell>
                              <TableCell>
                                <div className="flex space-x-2">
                                  <Link href={`/books/${book.bookId}`}>
                                    <Button variant="outline" size="icon" title="查看详情">
                                      <Eye className="h-4 w-4" />
                                    </Button>
                                  </Link>
                                  <Link href={`/admin/books/edit/${book.bookId}`}>
                                    <Button variant="outline" size="icon" title="编辑图书">
                                      <Edit className="h-4 w-4" />
                                    </Button>
                                  </Link>
                                  <Button
                                    variant="outline"
                                    size="icon"
                                    className="text-destructive"
                                    title="删除图书"
                                    onClick={() => handleDeleteBook(book.bookId)}
                                  >
                                    <Trash2 className="h-4 w-4" />
                                  </Button>
                                </div>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>

                    {books.total > books.pageSize && (
                      <Pagination className="mt-6">
                        <PaginationContent>
                          <PaginationItem>
                            <PaginationPrevious
                              href="#"
                              onClick={(e) => {
                                e.preventDefault()
                                if (currentPage > 1) handlePageChange(currentPage - 1)
                              }}
                              className={currentPage === 1 ? "pointer-events-none opacity-50" : ""}
                            />
                          </PaginationItem>

                          {Array.from({ length: Math.min(5, Math.ceil(books.total / books.pageSize)) }).map(
                            (_, index) => {
                              let pageNumber = currentPage - 2 + index
                              if (pageNumber < 1) pageNumber = index + 1
                              if (pageNumber > Math.ceil(books.total / books.pageSize))
                                pageNumber = Math.ceil(books.total / books.pageSize) - (4 - index)

                              return (
                                <PaginationItem key={index}>
                                  <PaginationLink
                                    href="#"
                                    onClick={(e) => {
                                      e.preventDefault()
                                      handlePageChange(pageNumber)
                                    }}
                                    isActive={currentPage === pageNumber}
                                  >
                                    {pageNumber}
                                  </PaginationLink>
                                </PaginationItem>
                              )
                            },
                          )}

                          <PaginationItem>
                            <PaginationNext
                              href="#"
                              onClick={(e) => {
                                e.preventDefault()
                                if (currentPage < Math.ceil(books.total / books.pageSize)) {
                                  handlePageChange(currentPage + 1)
                                }
                              }}
                              className={
                                currentPage >= Math.ceil(books.total / books.pageSize)
                                  ? "pointer-events-none opacity-50"
                                  : ""
                              }
                            />
                          </PaginationItem>
                        </PaginationContent>
                      </Pagination>
                    )}
                  </>
                )}
              </CardContent>
            </Card>
          </div>
        </main>
      </div>
    </div>
  )
}
