"use client"

import { useState, useEffect, useCallback } from "react"
import { DashboardShell } from "@/components/dashboard-shell"
import { DashboardHeader } from "@/components/dashboard-header"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Badge } from "@/components/ui/badge"
import { Search, Edit, Eye, Loader2, Archive } from "lucide-react"
import { AddHomeDecorDialog } from "@/components/home-decor/add-home-decor-dialog"
import type { HomeDecor as ComponentHomeDecor } from "@/components/home-decor/home-decor-detail-dialog"
import { DeleteConfirmationDialog } from "@/components/delete-confirmation-dialog"
import { PublishConfirmationDialog } from "@/components/publish-confirmation-dialog"
import { useToast } from "@/components/ui/use-toast"
import { isSuperUser } from "@/lib/api/auth"
import { getHomeDecors, deleteHomeDecor, publishHomeDecor, archiveHomeDecor } from "@/lib/api/home-decor"
import type { HomeDecor } from "@/lib/api/types"
import Link from "next/link"

// 格式化日期时间
function formatDate(dateStr: string): string {
  if (!dateStr) return ""
  try {
    return new Date(dateStr).toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
    })
  } catch {
    return dateStr
  }
}

// 将 API HomeDecor 转换为组件显示用的 HomeDecor
function toDisplayDecor(decor: HomeDecor): ComponentHomeDecor {
  return {
    id: decor.id,
    name: decor.name,
    type: decor.category || "",
    rarity: decor.rarity || "",
    description: decor.description || "",
    releaseDate: formatDate(decor.publishedAt || decor.createdAt || ""),
    status: decor.status || "未发布",
    activatedCount: decor.activeCardsCount || 0,
    image: decor.imageUrl || "/placeholder.svg?height=300&width=300",
  }
}

export default function HomeDecorPage() {
  const { toast } = useToast()
  const [decors, setDecors] = useState<ComponentHomeDecor[]>([])
  const [searchTerm, setSearchTerm] = useState("")
  const [currentPage, setCurrentPage] = useState(1)
  const [totalItems, setTotalItems] = useState(0)
  const [selectedDecor, setSelectedDecor] = useState<ComponentHomeDecor | null>(null)
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
  const [loading, setLoading] = useState(true)

  const itemsPerPage = 10

  // 从后端获取家居装饰列表
  const fetchDecors = useCallback(async () => {
    try {
      setLoading(true)
      const response = await getHomeDecors({
        page: currentPage,
        pageSize: itemsPerPage,
        search: searchTerm || undefined,
      })
      setDecors(response.items.map(toDisplayDecor))
      setTotalItems(response.total)
    } catch (error) {
      console.error("获取家居装饰列表失败:", error)
      toast({
        title: "获取失败",
        description: "无法获取家居装饰列表，请稍后重试",
        variant: "destructive",
      })
    } finally {
      setLoading(false)
    }
  }, [currentPage, searchTerm, toast])

  useEffect(() => {
    fetchDecors()
  }, [fetchDecors])

  const totalPages = Math.ceil(totalItems / itemsPerPage)

  // 处理添加家居装饰
  const handleAddDecor = (newDecor: ComponentHomeDecor) => {
    fetchDecors()
    toast({
      title: "添加成功",
      description: `家居装饰 ${newDecor.name} 已成功添加`,
    })
  }

  // 处理编辑家居装饰
  const handleEditDecor = (updatedDecor: ComponentHomeDecor) => {
    fetchDecors()
    setSelectedDecor(null)
    setIsEditDialogOpen(false)
    toast({
      title: "更新成功",
      description: `家居装饰 ${updatedDecor.name} 已成功更新`,
    })
  }

  // 处理删除家居装饰
  const handleDeleteDecor = async (decorId: string) => {
    try {
      await deleteHomeDecor(decorId)
      await fetchDecors()
      toast({
        title: "删除成功",
        description: "家居装饰已成功删除",
        variant: "destructive",
      })
    } catch (error) {
      console.error("删除家居装饰失败:", error)
      toast({
        title: "删除失败",
        description: "无法删除家居装饰，请稍后重试",
        variant: "destructive",
      })
    }
  }

  // 发布家居装饰
  const handlePublishDecor = async (decorId: string, decorName: string) => {
    try {
      await publishHomeDecor(decorId)
      await fetchDecors()
      toast({
        title: "发布成功",
        description: `家居装饰 "${decorName}" 已成功发布`,
      })
    } catch (error) {
      console.error("发布家居装饰失败:", error)
      toast({
        title: "发布失败",
        description: "无法发布家居装饰，请稍后重试",
        variant: "destructive",
      })
    }
  }

  // 归档家居装饰
  const handleArchiveDecor = async (decorId: string, decorName: string) => {
    try {
      await archiveHomeDecor(decorId)
      await fetchDecors()
      toast({
        title: "归档成功",
        description: `家居装饰 "${decorName}" 已归档`,
      })
    } catch (error) {
      console.error("归档家居装饰失败:", error)
      toast({
        title: "归档失败",
        description: "无法归档家居装饰，请稍后重试",
        variant: "destructive",
      })
    }
  }

  // 打开编辑对话框
  const openEditDialog = (decor: ComponentHomeDecor) => {
    setSelectedDecor(decor)
    setIsEditDialogOpen(true)
  }

  return (
    <DashboardShell>
      <DashboardHeader heading="家居装饰管理" text="管理洛天依的家居装饰卡牌">
        <AddHomeDecorDialog onSave={handleAddDecor} />
      </DashboardHeader>

      <div className="flex items-center justify-between space-y-2 mb-6">
        <div className="flex items-center space-x-2">
          <div className="relative">
            <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
            <Input
              type="search"
              placeholder="搜索家居装饰..."
              className="w-[300px] pl-8 border-none bg-white shadow-md focus-visible:ring-pink-500"
              value={searchTerm}
              onChange={(e) => {
                setSearchTerm(e.target.value)
                setCurrentPage(1)
              }}
            />
          </div>
        </div>
      </div>

      <Card className="border-none shadow-lg bg-gradient-to-br from-white to-purple-50">
        <CardHeader>
          <CardTitle className="text-xl font-bold flex items-center">
            <span className="bg-clip-text text-transparent bg-gradient-to-r from-purple-600 to-pink-600">家居装饰列表</span>
            <div className="ml-2 h-1 w-10 bg-gradient-to-r from-purple-600 to-pink-600 rounded-full"></div>
          </CardTitle>
          <CardDescription>管理洛天依的家居装饰卡牌</CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex items-center justify-center h-48">
              <Loader2 className="h-8 w-8 animate-spin text-pink-500" />
              <span className="ml-2 text-muted-foreground">加载中...</span>
            </div>
          ) : (
            <Table>
              <TableHeader className="bg-gray-50">
                <TableRow>
                  <TableHead className="w-[100px]">ID</TableHead>
                  <TableHead>装饰名称</TableHead>
                  <TableHead>类型</TableHead>
                  <TableHead>稀有度</TableHead>
                  <TableHead>发布日期</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>激活数量</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {decors.map((decor) => (
                  <TableRow key={decor.id} className="hover:bg-gray-50 transition-colors">
                    <TableCell className="font-medium">{decor.id}</TableCell>
                    <TableCell className="font-medium text-pink-600">{decor.name}</TableCell>
                    <TableCell>{decor.type}</TableCell>
                    <TableCell>{decor.rarity}</TableCell>
                    <TableCell>{decor.releaseDate || "-"}</TableCell>
                    <TableCell>
                      <Badge
                        className={
                          decor.status === "已发布"
                            ? "bg-green-500 hover:bg-green-600"
                            : decor.status === "已归档"
                              ? "bg-orange-500 hover:bg-orange-600"
                              : "bg-gray-500 hover:bg-gray-600"
                        }
                      >
                        {decor.status}
                      </Badge>
                    </TableCell>
                    <TableCell className="font-medium">{decor.activatedCount}</TableCell>
                    <TableCell className="text-right">
                      <Button variant="ghost" size="icon" className="hover:bg-pink-50 hover:text-pink-600" asChild>
                        <Link href={`/home-decor/${decor.id}`}>
                          <Eye className="h-4 w-4" />
                          <span className="sr-only">查看详情</span>
                        </Link>
                      </Button>

                      {/* 草稿状态：显示发布按钮 */}
                      {decor.status === "草稿" && (
                        <PublishConfirmationDialog
                          title="发布家居装饰"
                          description="发布后该家居装饰将可被用于卡牌生成"
                          itemName={decor.name}
                          onPublish={() => handlePublishDecor(decor.id, decor.name)}
                        />
                      )}

                      {/* 已发布状态：显示归档按钮 */}
                      {decor.status === "已发布" && (
                        <Button
                          variant="ghost"
                          size="icon"
                          className="hover:bg-orange-50 hover:text-orange-600"
                          title="归档"
                          onClick={() => handleArchiveDecor(decor.id, decor.name)}
                        >
                          <Archive className="h-4 w-4" />
                        </Button>
                      )}

                      {(decor.status !== "已发布" || isSuperUser()) && (
                        <>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="hover:bg-pink-50 hover:text-pink-600"
                            onClick={() => openEditDialog(decor)}
                          >
                            <Edit className="h-4 w-4" />
                          </Button>

                          <DeleteConfirmationDialog
                            title="删除家居装饰"
                            description="此操作将永久删除该家居装饰及其所有相关数据。"
                            itemName={decor.name}
                            onDelete={() => handleDeleteDecor(decor.id)}
                          />
                        </>
                      )}
                    </TableCell>
                  </TableRow>
                ))}

                {decors.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={8} className="h-24 text-center">
                      没有找到匹配的家居装饰
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          )}
        </CardContent>
        <CardFooter className="flex justify-between">
          <div className="text-sm text-muted-foreground">
            显示 {decors.length > 0 ? (currentPage - 1) * itemsPerPage + 1 : 0}-
            {Math.min(currentPage * itemsPerPage, totalItems)} 共 {totalItems} 个家居装饰
          </div>
          <div className="flex items-center space-x-2">
            <Button
              variant="outline"
              size="sm"
              className="hover:bg-pink-50 hover:text-pink-700 transition-all duration-200"
              onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
              disabled={currentPage === 1}
            >
              上一页
            </Button>
            <Button
              variant="outline"
              size="sm"
              className="hover:bg-pink-50 hover:text-pink-700 transition-all duration-200"
              onClick={() => setCurrentPage((prev) => Math.min(prev + 1, totalPages))}
              disabled={currentPage === totalPages || totalPages === 0}
            >
              下一页
            </Button>
          </div>
        </CardFooter>
      </Card>

      {/* 编辑家居装饰对话框 - 当选中家居装饰时显示 */}
      {selectedDecor && isEditDialogOpen && (
        <AddHomeDecorDialog
          mode="edit"
          initialDecor={selectedDecor}
          open={isEditDialogOpen}
          onOpenChange={setIsEditDialogOpen}
          onSave={handleEditDecor}
        />
      )}
    </DashboardShell>
  )
}
