"use client"

import { useState } 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 } from "lucide-react"
import { AddHomeDecorDialog } from "@/components/home-decor/add-home-decor-dialog"
import { DeleteConfirmationDialog } from "@/components/delete-confirmation-dialog"
import { useToast } from "@/components/ui/use-toast"
import Link from "next/link"
import type { HomeDecor } from "@/components/home-decor/home-decor-detail-dialog"

// 初始家居装饰数据
const initialDecors: HomeDecor[] = [
  {
    id: "DEC001",
    name: "星空投影灯",
    type: "灯饰",
    rarity: "稀有",
    description: "可以在房间内投影出美丽的星空，营造浪漫氛围。",
    releaseDate: "2023-10-20",
    status: "已发布",
    activatedCount: 1342,
    image: "/placeholder.svg?height=300&width=300",
  },
  {
    id: "DEC002",
    name: "音乐主题壁纸",
    type: "墙饰",
    rarity: "普通",
    description: "以音乐元素为主题的壁纸，适合洛天依的房间装饰。",
    releaseDate: "2023-11-05",
    status: "已发布",
    activatedCount: 2156,
    image: "/placeholder.svg?height=300&width=300",
  },
  {
    id: "DEC003",
    name: "音符地毯",
    type: "地饰",
    rarity: "稀有",
    description: "音符形状的地毯，踩上去会发出悦耳的音符声。",
    releaseDate: "2023-12-15",
    status: "已发布",
    activatedCount: 987,
    image: "/placeholder.svg?height=300&width=300",
  },
  {
    id: "DEC004",
    name: "全息投影装置",
    type: "科技装饰",
    rarity: "传说",
    description: "可以投影出洛天依的全息影像，实现虚拟互动。",
    releaseDate: "2024-01-20",
    status: "已发布",
    activatedCount: 456,
    image: "/placeholder.svg?height=300&width=300",
  },
  {
    id: "DEC005",
    name: "樱花主题家具套装",
    type: "家具套装",
    rarity: "史诗",
    description: "以樱花为主题的家具套装，包含床、桌椅、柜子等多件家具。",
    releaseDate: "",
    status: "未发布",
    activatedCount: 0,
    image: "/placeholder.svg?height=300&width=300",
  },
]

export default function HomeDecorPage() {
  const { toast } = useToast()
  const [decors, setDecors] = useState<HomeDecor[]>(initialDecors)
  const [searchTerm, setSearchTerm] = useState("")
  const [currentPage, setCurrentPage] = useState(1)
  const [selectedDecor, setSelectedDecor] = useState<HomeDecor | null>(null)
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)

  const itemsPerPage = 5

  // 过滤和分页
  const filteredDecors = decors.filter(
    (decor) =>
      decor.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      decor.id.toLowerCase().includes(searchTerm.toLowerCase()) ||
      decor.type.toLowerCase().includes(searchTerm.toLowerCase()),
  )

  const totalPages = Math.ceil(filteredDecors.length / itemsPerPage)
  const paginatedDecors = filteredDecors.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage)

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

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

  // 处理删除家居装饰
  const handleDeleteDecor = async (decorId: string) => {
    // 模拟API请求
    await new Promise((resolve) => setTimeout(resolve, 1000))

    setDecors((prevDecors) => prevDecors.filter((decor) => decor.id !== decorId))
    toast({
      title: "删除成功",
      description: "家居装饰已成功删除",
      variant: "destructive",
    })
  }

  // 打开编辑对话框
  const openEditDialog = (decor: HomeDecor) => {
    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>
          <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>
              {paginatedDecors.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" : "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 !== "已发布" && (
                      <>
                        <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>
              ))}

              {paginatedDecors.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">
            显示 {paginatedDecors.length > 0 ? (currentPage - 1) * itemsPerPage + 1 : 0}-
            {Math.min(currentPage * itemsPerPage, filteredDecors.length)} 共 {filteredDecors.length} 个家居装饰
          </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>
  )
}
