"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 { 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, Lock, Search, Shield, ShieldAlert, ShieldCheck, Unlock } from "lucide-react"
import { useRouter } from "next/navigation"
import { useEffect, useState } from "react"
import { fetchWithAuth } from "@/lib/api"

interface Reader {
  readerId: number
  username: string
  email: string
  phone: string
  isAdmin: boolean
  isBanned: boolean
}

export default function AdminUsersPage() {
  const { user } = useAuth()
  const router = useRouter()
  const { toast } = useToast()
  const [readers, setReaders] = useState<Reader[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState("")
  const [filteredReaders, setFilteredReaders] = useState<Reader[]>([])

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

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

    const fetchReaders = async () => {
      try {
        const response = await fetchWithAuth("reader/admin/all")
        const result = await response.json()

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

    fetchReaders()
  }, [user, router, toast])

  useEffect(() => {
    if (searchTerm) {
      const filtered = readers.filter(
        (reader) =>
          reader.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
          reader.email.toLowerCase().includes(searchTerm.toLowerCase()),
      )
      setFilteredReaders(filtered)
    } else {
      setFilteredReaders(readers)
    }
  }, [searchTerm, readers])

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

  const handleToggleAdmin = async (readerId: number, isAdmin: boolean) => {
    try {
      const url = isAdmin ? `reader/admin/${readerId}/remove-admin` : `reader/admin/${readerId}/make-admin`

      const response = await fetchWithAuth(url, {
        method: "PUT",
      })

      const result = await response.json()

      if (result.code === 0) {
        toast({
          title: "操作成功",
          description: isAdmin ? "已移除管理员权限" : "已设为管理员",
        })

        // 更新本地状态
        const updatedReaders = readers.map((reader) =>
          reader.readerId === readerId ? { ...reader, isAdmin: !isAdmin } : reader,
        )
        setReaders(updatedReaders)

        // 如果有搜索词，也更新过滤后的列表
        if (searchTerm) {
          const updatedFiltered = filteredReaders.map((reader) =>
            reader.readerId === readerId ? { ...reader, isAdmin: !isAdmin } : reader,
          )
          setFilteredReaders(updatedFiltered)
        }
      } else {
        toast({
          variant: "destructive",
          title: "操作失败",
          description: result.msg || "无法更改用户权限",
        })
      }
    } catch (error) {
      toast({
        variant: "destructive",
        title: "操作失败",
        description: "服务器连接错误，请稍后再试",
      })
    }
  }

  const handleToggleBan = async (readerId: number, isBanned: boolean) => {
    try {
      const url = isBanned ? `reader/admin/${readerId}/unban` : `reader/admin/${readerId}/ban`

      const response = await fetchWithAuth(url, {
        method: "PUT",
      })

      const result = await response.json()

      if (result.code === 0) {
        toast({
          title: "操作成功",
          description: isBanned ? "已解除封禁" : "已封禁用户",
        })

        // 更新本地状态
        const updatedReaders = readers.map((reader) =>
          reader.readerId === readerId ? { ...reader, isBanned: !isBanned } : reader,
        )
        setReaders(updatedReaders)

        // 如果有搜索词，也更新过滤后的列表
        if (searchTerm) {
          const updatedFiltered = filteredReaders.map((reader) =>
            reader.readerId === readerId ? { ...reader, isBanned: !isBanned } : reader,
          )
          setFilteredReaders(updatedFiltered)
        }
      } 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">
            <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>
                ) : filteredReaders.length === 0 ? (
                  <div className="flex flex-col items-center justify-center py-12">
                    <Shield 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>
                  </div>
                ) : (
                  <div className="rounded-md border">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>ID</TableHead>
                          <TableHead>用户名</TableHead>
                          <TableHead>邮箱</TableHead>
                          <TableHead>电话</TableHead>
                          <TableHead>状态</TableHead>
                          <TableHead>角色</TableHead>
                          <TableHead>操作</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {filteredReaders.map((reader) => (
                          <TableRow key={reader.readerId}>
                            <TableCell>{reader.readerId}</TableCell>
                            <TableCell className="font-medium">{reader.username}</TableCell>
                            <TableCell>{reader.email}</TableCell>
                            <TableCell>{reader.phone}</TableCell>
                            <TableCell>
                              {reader.isBanned ? (
                                <span className="flex items-center text-destructive">
                                  <Lock className="mr-1 h-4 w-4" />
                                  已封禁
                                </span>
                              ) : (
                                <span className="flex items-center text-green-600 dark:text-green-400">
                                  <Unlock className="mr-1 h-4 w-4" />
                                  正常
                                </span>
                              )}
                            </TableCell>
                            <TableCell>
                              {reader.isAdmin ? (
                                <span className="flex items-center text-amber-600 dark:text-amber-400">
                                  <ShieldAlert className="mr-1 h-4 w-4" />
                                  管理员
                                </span>
                              ) : (
                                <span className="flex items-center">
                                  <ShieldCheck className="mr-1 h-4 w-4" />
                                  普通用户
                                </span>
                              )}
                            </TableCell>
                            <TableCell>
                              <div className="flex space-x-2">
                                <Button
                                  variant="outline"
                                  size="sm"
                                  onClick={() => handleToggleAdmin(reader.readerId, reader.isAdmin)}
                                  disabled={reader.readerId === user.readerId}
                                >
                                  {reader.isAdmin ? "移除管理员" : "设为管理员"}
                                </Button>
                                <Button
                                  variant={reader.isBanned ? "outline" : "destructive"}
                                  size="sm"
                                  onClick={() => handleToggleBan(reader.readerId, reader.isBanned)}
                                  disabled={reader.readerId === user.readerId}
                                >
                                  {reader.isBanned ? "解除封禁" : "封禁"}
                                </Button>
                              </div>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </main>
      </div>
    </div>
  )
}
