"use client"

import { useState, useEffect, use } from "react"
import { DashboardShell } from "@/components/dashboard-shell"
import { DashboardHeader } from "@/components/dashboard-header"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { ArrowLeft, Edit, AlertTriangle, Plus, Download, Loader2 } from "lucide-react"
import Link from "next/link"
import { AddPrintBatchDialog } from "@/components/home-decor/add-print-batch-dialog"
import { ExportCardsDialog } from "@/components/home-decor/export-cards-dialog"
import { isSuperUser } from "@/lib/api/auth"
import { getHomeDecor } from "@/lib/api/home-decor"
import type { HomeDecor } from "@/lib/api/types"

export default function HomeDecorDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params)
  const [decor, setDecor] = useState<HomeDecor | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchDecor = async () => {
      try {
        setLoading(true)
        setError(null)
        const data = await getHomeDecor(id)
        setDecor(data)
      } catch (err) {
        console.error("获取家居装饰详情失败:", err)
        setError(`找不到ID为 ${id} 的家居装饰`)
      } finally {
        setLoading(false)
      }
    }
    fetchDecor()
  }, [id])

  if (loading) {
    return (
      <DashboardShell>
        <div className="flex items-center justify-center h-[60vh]">
          <Loader2 className="h-8 w-8 animate-spin text-pink-500" />
          <span className="ml-2 text-muted-foreground">加载中...</span>
        </div>
      </DashboardShell>
    )
  }

  if (error || !decor) {
    return (
      <DashboardShell>
        <div className="flex flex-col items-center justify-center h-[60vh]">
          <AlertTriangle className="h-16 w-16 text-red-500 mb-4" />
          <h1 className="text-2xl font-bold mb-2">家居装饰不存在</h1>
          <p className="text-gray-500 mb-6">{error || `找不到ID为 ${id} 的家居装饰`}</p>
          <Button asChild>
            <Link href="/home-decor">
              <ArrowLeft className="mr-2 h-4 w-4" />
              返回家居装饰列表
            </Link>
          </Button>
        </div>
      </DashboardShell>
    )
  }

  const isPublished = decor.status === "已发布"
  const printedCount = decor.batchesCount || 0
  const activatedCount = decor.activeCardsCount || 0
  const activationRate = printedCount > 0 ? Math.round((activatedCount / printedCount) * 100) : 0

  return (
    <DashboardShell>
      <div className="absolute top-0 right-0 w-1/2 h-48 bg-gradient-to-bl from-purple-200 via-pink-200 to-transparent opacity-20 rounded-bl-full" />

      <div className="flex items-center mb-6">
        <Button variant="ghost" size="sm" className="mr-4" asChild>
          <Link href="/home-decor">
            <ArrowLeft className="mr-2 h-4 w-4" />
            返回列表
          </Link>
        </Button>
        <DashboardHeader heading={decor.name} text={`家居装饰ID: ${decor.id}`}>
          <div className="flex space-x-2 ml-auto">
            {(!isPublished || isSuperUser()) && (
              <Button
                asChild
                className="bg-gradient-to-r from-pink-500 to-purple-600 hover:from-pink-600 hover:to-purple-700 transition-all duration-300 shadow-md hover:shadow-lg"
              >
                <Link href={`/home-decor/edit/${id}`}>
                  <Edit className="mr-2 h-4 w-4" />
                  编辑家居装饰
                </Link>
              </Button>
            )}
            <ExportCardsDialog decorId={decor.id} />
          </div>
        </DashboardHeader>
      </div>

      <Tabs defaultValue="details" className="w-full">
        <TabsList className="grid w-full md:w-auto grid-cols-2 md:grid-cols-3 mb-4">
          <TabsTrigger value="details">家居装饰详情</TabsTrigger>
          <TabsTrigger value="batches">批次管理</TabsTrigger>
          <TabsTrigger value="analytics">数据分析</TabsTrigger>
        </TabsList>

        <TabsContent value="details" className="space-y-6">
          <div className="grid gap-6 md:grid-cols-3">
            <Card className="md:col-span-1 border-none shadow-lg bg-white">
              <CardHeader>
                <CardTitle className="text-lg font-bold">家居装饰预览</CardTitle>
              </CardHeader>
              <CardContent className="flex justify-center">
                <div className="relative w-full aspect-square max-w-[300px] rounded-lg overflow-hidden bg-gray-100 flex items-center justify-center">
                  {decor.imageUrl && !decor.imageUrl.includes("placeholder") ? (
                    <img src={decor.imageUrl} alt={decor.name} className="object-cover w-full h-full" />
                  ) : (
                    <div className="flex flex-col items-center justify-center text-gray-400">
                      <svg className="h-16 w-16 mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909M3.75 21h16.5A2.25 2.25 0 0022.5 18.75V5.25A2.25 2.25 0 0020.25 3H3.75A2.25 2.25 0 001.5 5.25v13.5A2.25 2.25 0 003.75 21z" />
                      </svg>
                      <span className="text-sm">暂无图片</span>
                    </div>
                  )}
                  <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-3">
                    <Badge className={`${isPublished ? "bg-green-500" : "bg-gray-500"}`}>{decor.status || "未发布"}</Badge>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="md:col-span-2 border-none shadow-lg bg-gradient-to-br from-white to-purple-50">
              <CardHeader>
                <CardTitle className="text-lg font-bold">家居装饰详情</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <p className="text-sm font-medium text-gray-500">装饰类型</p>
                    <p className="font-medium">{decor.category || "-"}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm font-medium text-gray-500">稀有度</p>
                    <p className="font-medium">{decor.rarity || "-"}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm font-medium text-gray-500">发布日期</p>
                    <p className="font-medium">{decor.publishedAt || "尚未发布"}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm font-medium text-gray-500">激活数量</p>
                    <p className="font-medium">{activatedCount}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm font-medium text-gray-500">创建日期</p>
                    <p className="font-medium">{decor.createdAt || "-"}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm font-medium text-gray-500">激活率</p>
                    <p className="font-medium">{activationRate}%</p>
                  </div>
                </div>

                <div className="mt-6">
                  <p className="text-sm font-medium text-gray-500 mb-2">装饰描述</p>
                  <p className="text-gray-700">{decor.description || "暂无描述"}</p>
                </div>

                {isPublished && (
                  <div className="mt-6 p-3 bg-amber-50 border border-amber-200 rounded-lg flex items-start">
                    <AlertTriangle className="h-5 w-5 text-amber-500 mr-2 flex-shrink-0 mt-0.5" />
                    <p className="text-sm text-amber-700">
                      {isSuperUser()
                        ? "该家居装饰已发布，您以超级管理员身份仍可编辑和删除。请谨慎操作。"
                        : "该家居装饰已发布，基本属性不可修改。您仍可以增加印刷数量。"}
                    </p>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="batches" className="space-y-6">
          <Card className="border-none shadow-lg bg-gradient-to-br from-white to-blue-50">
            <CardHeader className="flex flex-row items-center justify-between">
              <div>
                <CardTitle className="text-lg font-bold">印刷批次管理</CardTitle>
                <CardDescription>管理家居装饰卡牌的印刷批次和卡牌ID</CardDescription>
              </div>
              <AddPrintBatchDialog decorId={decor.id} isPublished={isPublished} />
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <table className="w-full">
                  <thead>
                    <tr className="bg-gray-50 border-b">
                      <th className="py-3 px-4 text-left text-sm font-medium text-gray-500">批次ID</th>
                      <th className="py-3 px-4 text-left text-sm font-medium text-gray-500">创建日期</th>
                      <th className="py-3 px-4 text-left text-sm font-medium text-gray-500">数量</th>
                      <th className="py-3 px-4 text-left text-sm font-medium text-gray-500">状态</th>
                      <th className="py-3 px-4 text-right text-sm font-medium text-gray-500">操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td colSpan={5} className="py-8 text-center text-gray-500">
                        批次数据将从后端加载
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>

          <Card className="border-none shadow-lg bg-white">
            <CardHeader>
              <CardTitle className="text-lg font-bold">批次操作</CardTitle>
              <CardDescription>批量管理卡牌批次</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex flex-wrap gap-4">
                <Button variant="outline" className="border-blue-200 hover:bg-blue-50 hover:text-blue-700">
                  <Download className="mr-2 h-4 w-4" />
                  导出所有批次
                </Button>
                <Button variant="outline" className="border-purple-200 hover:bg-purple-50 hover:text-purple-700">
                  <Plus className="mr-2 h-4 w-4" />
                  批量添加批次
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="analytics" className="space-y-6">
          <Card className="border-none shadow-lg bg-white">
            <CardHeader>
              <CardTitle className="text-lg font-bold">激活数据分析</CardTitle>
              <CardDescription>家居装饰卡牌激活情况统计</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="h-[300px] flex items-center justify-center bg-gray-50 rounded-lg">
                <p className="text-gray-500">激活数据图表将在此显示</p>
              </div>
            </CardContent>
          </Card>

          <div className="grid gap-6 md:grid-cols-2">
            <Card className="border-none shadow-lg bg-gradient-to-br from-white to-green-50">
              <CardHeader>
                <CardTitle className="text-lg font-bold">地区分布</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="h-[200px] flex items-center justify-center bg-gray-50 rounded-lg">
                  <p className="text-gray-500">地区分布图表将在此显示</p>
                </div>
              </CardContent>
            </Card>

            <Card className="border-none shadow-lg bg-gradient-to-br from-white to-blue-50">
              <CardHeader>
                <CardTitle className="text-lg font-bold">时间趋势</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="h-[200px] flex items-center justify-center bg-gray-50 rounded-lg">
                  <p className="text-gray-500">时间趋势图表将在此显示</p>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>
    </DashboardShell>
  )
}
