"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, Eye, Search } from "lucide-react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { useEffect, useState } from "react"
import { fetchWithAuth } from "@/lib/api"

interface OrderItem {
  orderItemId: number
  bookId: number
  bookTitle: string
  quantity: number
  unitPrice: number
}

interface Order {
  orderId: number
  readerId: number
  readerName: string
  orderDate: string
  totalAmount: number
  status: string
  items: OrderItem[]
}

interface OrdersResponse {
  pageNum: number
  pageSize: number
  total: number
  data: Order[]
}

export default function AdminOrdersPage() {
  const { user } = useAuth()
  const router = useRouter()
  const { toast } = useToast()
  const [orders, setOrders] = useState<OrdersResponse | 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 fetchOrders = async () => {
      setLoading(true)
      try {
        const response = await fetchWithAuth(`orders/admin/all?pageNum=${currentPage}&pageSize=10`)
        const result = await response.json()

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

    fetchOrders()
  }, [user, router, toast, currentPage])

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

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault()
    // 实际项目中应该有搜索订单的API
    toast({
      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">
            <h1 className="text-3xl font-bold">订单管理</h1>

            <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>
                ) : !orders || orders.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">系统中还没有订单记录</p>
                  </div>
                ) : (
                  <>
                    <div className="rounded-md border">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>订单号</TableHead>
                            <TableHead>用户</TableHead>
                            <TableHead>下单时间</TableHead>
                            <TableHead>总金额</TableHead>
                            <TableHead>状态</TableHead>
                            <TableHead>操作</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {orders.data.map((order) => (
                            <TableRow key={order.orderId}>
                              <TableCell>{order.orderId}</TableCell>
                              <TableCell className="font-medium">{order.readerName}</TableCell>
                              <TableCell>{new Date(order.orderDate).toLocaleString()}</TableCell>
                              <TableCell>¥{order.totalAmount.toFixed(2)}</TableCell>
                              <TableCell>
                                <span className="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-green-100 text-green-800 dark:bg-green-800/20 dark:text-green-400">
                                  {order.status}
                                </span>
                              </TableCell>
                              <TableCell>
                                <Link href={`/orders/${order.orderId}`}>
                                  <Button variant="outline" size="sm">
                                    <Eye className="mr-2 h-4 w-4" />
                                    查看详情
                                  </Button>
                                </Link>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>

                    {orders.total > orders.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(orders.total / orders.pageSize)) }).map(
                            (_, index) => {
                              let pageNumber = currentPage - 2 + index
                              if (pageNumber < 1) pageNumber = index + 1
                              if (pageNumber > Math.ceil(orders.total / orders.pageSize))
                                pageNumber = Math.ceil(orders.total / orders.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(orders.total / orders.pageSize)) {
                                  handlePageChange(currentPage + 1)
                                }
                              }}
                              className={
                                currentPage >= Math.ceil(orders.total / orders.pageSize)
                                  ? "pointer-events-none opacity-50"
                                  : ""
                              }
                            />
                          </PaginationItem>
                        </PaginationContent>
                      </Pagination>
                    )}
                  </>
                )}
              </CardContent>
            </Card>
          </div>
        </main>
      </div>
    </div>
  )
}
