
import React, { useState, useEffect } from "react";
import { createPageUrl } from "@/utils";
import { 
  Puzzle,
  TrendingUp, 
  Wand2, 
  History, 
  Eye, 
  Calendar,
  Zap,
  GalleryThumbnails,
  Search
} from "lucide-react";
import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarHeader,
  SidebarFooter,
  SidebarProvider,
  SidebarTrigger,
} from "@/components/ui/sidebar";
import { Badge } from "@/components/ui/badge";
import UserProfile from "@/components/auth/UserProfile";
import { useAuth } from "@/contexts/AuthContext";
import { getDashboardStats } from "@/api/dashboard";

const navigationItems = [
  {
    title: "模板管理",
    url: createPageUrl("TemplateManagement"),
    icon: Puzzle,
    color: "text-blue-600"
  },
  {
    title: "素材管理",
    url: createPageUrl("MaterialLibrary"),
    icon: GalleryThumbnails,
    color: "text-green-600"
  },
  {
    title: "平台热点",
    url: createPageUrl("HotTopics"),
    icon: TrendingUp,
    color: "text-red-600"
  },
  {
    title: "智能生成",
    url: createPageUrl("AIGeneration"),
    icon: Wand2,
    color: "text-purple-600"
  },
  {
    title: "结果浏览",
    url: createPageUrl("ContentBrowser"),
    icon: Eye,
    color: "text-indigo-600"
  },
  {
    title: "历史记录",
    url: createPageUrl("History"),
    icon: History,
    color: "text-gray-600"
  },
  {
    title: "素材检索",
    url: createPageUrl("AIAssetSearch"),
    icon: Search,
    color: "text-cyan-600"
  },
  {
    title: "自动发布",
    url: createPageUrl("AutoPublish"),
    icon: Calendar,
    color: "text-orange-600"
  },
];

export default function Layout({ children, currentPageName }) {
  const { user } = useAuth();
  const [stats, setStats] = useState({
    today_generated: 0,
    pending_review: 0,
    published: 0
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchStats = async () => {
      if (!user?.id) return;
      
      try {
        setLoading(true);
        const data = await getDashboardStats(user.id);
        setStats(data);
      } catch (err) {
        console.error('获取统计数据失败:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchStats();
    // 每5分钟刷新一次数据
    const interval = setInterval(fetchStats, 5 * 60 * 1000);
    return () => clearInterval(interval);
  }, [user?.id]);

  const getCurrentPageUrl = () => {
    return window.location.pathname;
  };

  const handleNavigation = (url) => {
    window.location.href = url;
  };

  return (
    <SidebarProvider>
      <div className="min-h-screen flex w-full bg-gradient-to-br from-slate-50 to-blue-50">
        <Sidebar className="border-r border-slate-200/60 bg-white/80 backdrop-blur-xl">
          <SidebarHeader className="border-b border-slate-200/60 p-6">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-gradient-to-br from-blue-600 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
                <Zap className="w-6 h-6 text-white" />
              </div>
              <div>
                <h2 className="font-bold text-slate-900 text-lg">矩阵营销</h2>
                <p className="text-xs text-slate-500">智能素材生成平台</p>
              </div>
            </div>
          </SidebarHeader>
          
          <SidebarContent className="p-4">
            <SidebarGroup>
              <SidebarGroupLabel className="text-xs font-semibold text-slate-500 uppercase tracking-wider px-3 py-2">
                主要功能
              </SidebarGroupLabel>
              <SidebarGroupContent className="space-y-1">
                <SidebarMenu>
                  {navigationItems.map((item) => (
                    <SidebarMenuItem key={item.title}>
                      <SidebarMenuButton 
                        onClick={() => handleNavigation(item.url)}
                        className={`rounded-xl transition-all duration-200 hover:bg-slate-100 cursor-pointer ${
                          getCurrentPageUrl() === item.url 
                            ? 'bg-gradient-to-r from-blue-50 to-purple-50 text-blue-700 shadow-sm' 
                            : 'text-slate-700 hover:text-slate-900'
                        }`}
                      >
                        <div className="flex items-center gap-3 px-4 py-3">
                          <item.icon className={`w-5 h-5 ${item.color}`} />
                          <span className="font-medium">{item.title}</span>
                        </div>
                      </SidebarMenuButton>
                    </SidebarMenuItem>
                  ))}
                </SidebarMenu>
              </SidebarGroupContent>
            </SidebarGroup>

            <SidebarGroup className="mt-6">
              <SidebarGroupLabel className="text-xs font-semibold text-slate-500 uppercase tracking-wider px-3 py-2">
                平台状态
              </SidebarGroupLabel>
              <SidebarGroupContent>
                <div className="px-3 py-2 space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-slate-600">今日生成</span>
                    <Badge variant="secondary" className="bg-blue-100 text-blue-700">
                      {loading ? '...' : stats.today_generated}
                    </Badge>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-slate-600">待审核</span>
                    <Badge variant="secondary" className="bg-amber-100 text-amber-700">
                      {loading ? '...' : stats.pending_review}
                    </Badge>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-slate-600">已发布</span>
                    <Badge variant="secondary" className="bg-green-100 text-green-700">
                      {loading ? '...' : stats.published}
                    </Badge>
                  </div>
                </div>
              </SidebarGroupContent>
            </SidebarGroup>
          </SidebarContent>

          <SidebarFooter className="border-t border-slate-200/60 p-4">
            <UserProfile />
          </SidebarFooter>
        </Sidebar>

        <main className="flex-1 flex flex-col">
          <header className="bg-white/80 backdrop-blur-xl border-b border-slate-200/60 px-6 py-4 md:hidden">
            <div className="flex items-center gap-4">
              <SidebarTrigger className="hover:bg-slate-100 p-2 rounded-lg transition-colors duration-200" />
              <h1 className="text-xl font-bold text-slate-900">矩阵营销</h1>
            </div>
          </header>

          <div className="flex-1 overflow-auto">
            {children}
          </div>
        </main>
      </div>
    </SidebarProvider>
  );
}
