"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 {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Textarea } from "@/components/ui/textarea"
import { useToast } from "@/components/ui/use-toast"
import { useAuth } from "@/context/auth-context"
import { zodResolver } from "@hookform/resolvers/zod"
import { BookOpen, Edit, Plus, Search, Trash2 } from "lucide-react"
import { useRouter } from "next/navigation"
import { useEffect, useState } from "react"
import { useForm } from "react-hook-form"
import * as z from "zod"
import { fetchWithAuth } from "@/lib/api"

interface Publisher {
  publisherId: number
  name: string
  address: string
}

const formSchema = z.object({
  name: z.string().min(1, "出版社名称不能为空"),
  address: z.string().optional(),
})

export default function AdminPublishersPage() {
  const { user } = useAuth()
  const router = useRouter()
  const { toast } = useToast()
  const [publishers, setPublishers] = useState<Publisher[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState("")
  const [filteredPublishers, setFilteredPublishers] = useState<Publisher[]>([])
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
  const [currentPublisher, setCurrentPublisher] = useState<Publisher | null>(null)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const addForm = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: "",
      address: "",
    },
  })

  const editForm = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: "",
      address: "",
    },
  })

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

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

    const fetchPublishers = async () => {
      try {
        const response = await fetchWithAuth("publisher/all")
        const result = await response.json()

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

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

  useEffect(() => {
    if (searchTerm) {
      const filtered = publishers.filter((publisher) => publisher.name.toLowerCase().includes(searchTerm.toLowerCase()))
      setFilteredPublishers(filtered)
    } else {
      setFilteredPublishers(publishers)
    }
  }, [searchTerm, publishers])

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

  const handleAddPublisher = async (values: z.infer<typeof formSchema>) => {
    setIsSubmitting(true)
    try {
      const response = await fetchWithAuth("publisher/add", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(values),
      })

      const result = await response.json()

      if (result.code === 0) {
        toast({
          title: "添加成功",
          description: "出版社已成功添加",
        })

        // 更新本地状态
        setPublishers([...publishers, result.data])

        // 重置表单并关闭对话框
        addForm.reset()
        setIsAddDialogOpen(false)
      } else {
        toast({
          variant: "destructive",
          title: "添加失败",
          description: result.msg || "无法添加出版社",
        })
      }
    } catch (error) {
      toast({
        variant: "destructive",
        title: "添加失败",
        description: "服务器连接错误，请稍后再试",
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleEditPublisher = async (values: z.infer<typeof formSchema>) => {
    if (!currentPublisher) return

    setIsSubmitting(true)
    try {
      const response = await fetchWithAuth(`publisher/update/${currentPublisher.publisherId}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(values),
      })

      const result = await response.json()

      if (result.code === 0) {
        toast({
          title: "更新成功",
          description: "出版社信息已成功更新",
        })

        // 更新本地状态
        const updatedPublishers = publishers.map((publisher) =>
          publisher.publisherId === currentPublisher.publisherId ? result.data : publisher,
        )
        setPublishers(updatedPublishers)

        // 重置表单并关闭对话框
        editForm.reset()
        setIsEditDialogOpen(false)
        setCurrentPublisher(null)
      } else {
        toast({
          variant: "destructive",
          title: "更新失败",
          description: result.msg || "无法更新出版社信息",
        })
      }
    } catch (error) {
      toast({
        variant: "destructive",
        title: "更新失败",
        description: "服务器连接错误，请稍后再试",
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleDeletePublisher = async (publisherId: number) => {
    if (confirm("确定要删除这个出版社吗？此操作不可撤销。")) {
      try {
        const response = await fetchWithAuth(`publisher/delete/${publisherId}`, {
          method: "DELETE",
        })

        const result = await response.json()

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

          // 更新本地状态
          const updatedPublishers = publishers.filter((publisher) => publisher.publisherId !== publisherId)
          setPublishers(updatedPublishers)
        } else {
          toast({
            variant: "destructive",
            title: "删除失败",
            description: result.msg || "无法删除出版社",
          })
        }
      } catch (error) {
        toast({
          variant: "destructive",
          title: "删除失败",
          description: "服务器连接错误，请稍后再试",
        })
      }
    }
  }

  const openEditDialog = (publisher: Publisher) => {
    setCurrentPublisher(publisher)
    editForm.reset({
      name: publisher.name,
      address: publisher.address,
    })
    setIsEditDialogOpen(true)
  }

  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>
              <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
                <DialogTrigger asChild>
                  <Button>
                    <Plus className="mr-2 h-4 w-4" />
                    添加出版社
                  </Button>
                </DialogTrigger>
                <DialogContent>
                  <DialogHeader>
                    <DialogTitle>添加出版社</DialogTitle>
                    <DialogDescription>添加一个新的出版社到系统中</DialogDescription>
                  </DialogHeader>
                  <Form {...addForm}>
                    <form onSubmit={addForm.handleSubmit(handleAddPublisher)} className="space-y-4">
                      <FormField
                        control={addForm.control}
                        name="name"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>出版社名称</FormLabel>
                            <FormControl>
                              <Input placeholder="输入出版社名称" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={addForm.control}
                        name="address"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>地址</FormLabel>
                            <FormControl>
                              <Textarea placeholder="输入出版社地址" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <DialogFooter>
                        <Button type="submit" disabled={isSubmitting}>
                          {isSubmitting ? "提交中..." : "添加"}
                        </Button>
                      </DialogFooter>
                    </form>
                  </Form>
                </DialogContent>
              </Dialog>
            </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>
                ) : filteredPublishers.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 && (
                      <Button className="mt-4" onClick={() => setIsAddDialogOpen(true)}>
                        <Plus className="mr-2 h-4 w-4" />
                        添加出版社
                      </Button>
                    )}
                  </div>
                ) : (
                  <div className="rounded-md border">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>ID</TableHead>
                          <TableHead>名称</TableHead>
                          <TableHead>地址</TableHead>
                          <TableHead>操作</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {filteredPublishers.map((publisher) => (
                          <TableRow key={publisher.publisherId}>
                            <TableCell>{publisher.publisherId}</TableCell>
                            <TableCell className="font-medium">{publisher.name}</TableCell>
                            <TableCell>{publisher.address || "无"}</TableCell>
                            <TableCell>
                              <div className="flex space-x-2">
                                <Button variant="outline" size="icon" onClick={() => openEditDialog(publisher)}>
                                  <Edit className="h-4 w-4" />
                                </Button>
                                <Button
                                  variant="outline"
                                  size="icon"
                                  className="text-destructive"
                                  onClick={() => handleDeletePublisher(publisher.publisherId)}
                                >
                                  <Trash2 className="h-4 w-4" />
                                </Button>
                              </div>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>

          <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>编辑出版社</DialogTitle>
                <DialogDescription>修改出版社信息</DialogDescription>
              </DialogHeader>
              <Form {...editForm}>
                <form onSubmit={editForm.handleSubmit(handleEditPublisher)} className="space-y-4">
                  <FormField
                    control={editForm.control}
                    name="name"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>出版社名称</FormLabel>
                        <FormControl>
                          <Input placeholder="输入出版社名称" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={editForm.control}
                    name="address"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>地址</FormLabel>
                        <FormControl>
                          <Textarea placeholder="输入出版社地址" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <DialogFooter>
                    <Button type="submit" disabled={isSubmitting}>
                      {isSubmitting ? "提交中..." : "保存"}
                    </Button>
                  </DialogFooter>
                </form>
              </Form>
            </DialogContent>
          </Dialog>
        </main>
      </div>
    </div>
  )
}
