import { useState, useEffect, useRef } from "react";
import { useAuth } from "@/contexts/AuthContext";
import { useNavigate, useParams } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ProductsTabs } from "@/components/admin/ProductsTabs";

import { AfterSalesTabs } from "@/components/admin/aftersales";
import { FinanceTabs } from "@/components/admin/finance";
import { AdminAIAssistant } from "@/components/admin/AdminAIAssistant";

import { BannersManager } from "@/components/admin/BannersManager";

import { MarketingManager } from "@/components/admin/MarketingManager";
import { ManagerWorkbench } from "@/components/admin/manager";
import { EmailWorkbench } from "@/components/admin/email/EmailWorkbench";
import { AdminSidebar } from "@/components/admin/AdminSidebar";
import { MerchantOnboarding } from "@/components/admin/MerchantOnboarding";
import { RealtimeAlertBanner } from "@/components/admin/shared/RealtimeAlertBanner";
import ProductEditPage from "./ProductEditPage";
import CouponEditPage from "./CouponEditPage";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
import { ScrollArea } from "@/components/ui/scroll-area";
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@/components/ui/resizable";
import { useCapabilitiesSync } from "@/hooks/useCapabilitiesSync";
import { SectionErrorBoundary } from "@/components/SectionErrorBoundary";
import { ThemeToggle } from "@/components/theme/ThemeToggle";
import { 
  LogOut, 
  Home,
  Bot,
  PanelRightClose,
  PanelRightOpen,
  User as UserIcon
} from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { supabase } from "@/integrations/supabase/client";

export default function AdminPage() {
  const { user, profile, loading, signOut } = useAuth();
  const navigate = useNavigate();
  const { "*": splat } = useParams();
  
  // 自动同步能力定义到数据库
  useCapabilitiesSync();
  
  // 检测是否在编辑页面
  const isProductEdit = splat?.startsWith("products/");
  const productId = isProductEdit ? splat.split("/")[1] : null;
  const isCouponEdit = splat?.startsWith("coupons/");
  const couponId = isCouponEdit ? splat.split("/")[1] : null;
  
  // 从URL参数读取tab
  const [activeTab, setActiveTab] = useState(() => {
    const searchParams = new URLSearchParams(window.location.search);
    return isProductEdit ? "products" : 
      isCouponEdit ? "marketing" :
      (searchParams.get('tab') || "home");
  });
  
  // 监听URL变化，同步activeTab
  useEffect(() => {
    const searchParams = new URLSearchParams(window.location.search);
    const tabParam = searchParams.get('tab');
    if (tabParam && !isProductEdit && !isCouponEdit) {
      setActiveTab(tabParam);
    } else if (isProductEdit) {
      setActiveTab("products");
    } else if (isCouponEdit) {
      setActiveTab("marketing");
    }
  }, [splat, isProductEdit, isCouponEdit]);
  
  // 标题映射
  const tabTitles: Record<string, string> = {
    home: "店长工作台",
    "create-task": "新任务 · 快速开始",
    transactions: "财务工作台",
    products: "商品工作台",
    marketing: "营销工作台",
    aftersales: "客服工作台",
    email: "邮件工作台"
  };
  
  const [isAIPanelOpen, setIsAIPanelOpen] = useState(true);

  const [stats, setStats] = useState({
    totalProducts: 0,
    totalUsers: 0,
    totalOrders: 0,
    totalRevenue: 0,
    loading: true
  });

  // 获取统计数据
  useEffect(() => {
    const fetchStats = async () => {
      try {
        // 获取商品总数
        const { count: productsCount } = await supabase
          .from('products')
          .select('*', { count: 'exact', head: true })
          .eq('is_active', true);

        // 获取用户总数
        const { count: usersCount } = await supabase
          .from('profiles')
          .select('*', { count: 'exact', head: true });

        // 获取订单总数
        const { count: ordersCount } = await supabase
          .from('orders')
          .select('*', { count: 'exact', head: true });

        // 获取总销售额
        const { data: revenueData } = await supabase
          .from('orders')
          .select('total_amount')
          .not('status', 'eq', 'cancelled');

        const totalRevenue = revenueData?.reduce((sum, order) => sum + (order.total_amount || 0), 0) || 0;

        setStats({
          totalProducts: productsCount || 0,
          totalUsers: usersCount || 0,
          totalOrders: ordersCount || 0,
          totalRevenue,
          loading: false
        });
      } catch (error) {
        console.error('获取统计数据失败:', error);
        setStats(prev => ({ ...prev, loading: false }));
      }
    };

    if (user) {
      fetchStats();
    }
  }, [user]);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  const handleSignOut = async () => {
    await signOut();
  };

  // 处理tab切换，如果在编辑页面需要先导航回admin
  const handleTabChange = (tab: string) => {
    if (isProductEdit || isCouponEdit) {
      navigate(`/admin?tab=${tab}`);
    }
    setActiveTab(tab);
  };

  return (
    <SidebarProvider defaultOpen={false}>
      <div className="h-screen overflow-hidden bg-gradient-app flex w-full">
        {/* 左侧导航栏 */}
        <AdminSidebar activeTab={activeTab} onTabChange={handleTabChange} />

        {/* 主内容区域 */}
        <div className="flex-1 flex flex-col min-h-0">
          {/* 顶部栏 */}
          <header className="h-[49px] border-b border-border/60 bg-card/80 backdrop-blur-md flex-shrink-0 flex items-center shadow-xs">
            <div className="px-4 w-full">
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-4">
                  <SidebarTrigger />
                  <h1 className="text-base font-semibold text-primary">{tabTitles[activeTab]}</h1>
                </div>

                <div className="flex items-center space-x-4">
                  {/* AI面板切换 */}
                  {activeTab !== "create-task" && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => setIsAIPanelOpen(!isAIPanelOpen)}
                      className="flex items-center space-x-2"
                      title={isAIPanelOpen ? "收起AI助理" : "展开AI助理"}
                    >
                      {isAIPanelOpen ? (
                        <PanelRightClose className="h-4 w-4" />
                      ) : (
                        <PanelRightOpen className="h-4 w-4" />
                      )}
                      <span className="hidden sm:inline">AI助理</span>
                    </Button>
                  )}
                  
                  {/* 实时警报按钮 */}
                  <RealtimeAlertBanner />

                  {/* 主题切换 */}
                  <ThemeToggle size="sm" />

                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => navigate('/')}
                    className="flex items-center space-x-2"
                  >
                    <Home className="h-4 w-4" />
                    <span>返回前台</span>
                  </Button>
                  
                  <div className="h-6 w-px bg-border"></div>
                  
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" className="relative h-9 w-9 rounded-full">
                        <Avatar className="h-8 w-8">
                          <AvatarFallback className="bg-primary text-primary-foreground text-sm">
                            {profile?.display_name?.[0]?.toUpperCase() || "A"}
                          </AvatarFallback>
                        </Avatar>
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent className="w-56" align="end">
                      <DropdownMenuLabel className="font-normal">
                        <div className="flex flex-col space-y-1">
                          <p className="text-sm font-medium leading-none">
                            {profile?.display_name || "管理员"}
                          </p>
                          <p className="text-xs leading-none text-muted-foreground">
                            {user?.email}
                          </p>
                        </div>
                      </DropdownMenuLabel>
                      <DropdownMenuSeparator />
                      <DropdownMenuItem
                        onClick={() => {
                          const tabLabel = tabTitles[activeTab] || "管理后台";
                          const fromPath =
                            activeTab && activeTab !== "create-task"
                              ? `/admin/dashboard?tab=${activeTab}`
                              : "/admin/dashboard";
                          navigate("/admin/me", {
                            state: { from: { path: fromPath, label: tabLabel } },
                          });
                        }}
                      >
                        <UserIcon className="mr-2 h-4 w-4" />
                        我的
                      </DropdownMenuItem>
                      <DropdownMenuSeparator />
                      <DropdownMenuItem onClick={handleSignOut} className="text-destructive">
                        <LogOut className="mr-2 h-4 w-4" />
                        退出登录
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
              </div>
            </div>
          </header>

          {/* 主内容和右侧AI助理 - 使用 ResizablePanel 整合 */}
          <ResizablePanelGroup direction="horizontal" className="flex-1 min-h-0">
             <ResizablePanel defaultSize={activeTab === "create-task" || !isAIPanelOpen ? 100 : 70} minSize={40}>
              {activeTab === "email" && !isProductEdit && !isCouponEdit ? (
                /* 邮件工作台：不使用外层 ScrollArea，自己管理滚动 */
                <div className="h-full p-4 md:p-6 flex flex-col">
                  <div className="rounded-xl bg-card border border-card-border/60 shadow-sm p-4 md:p-6 flex-1 min-h-0 overflow-hidden flex flex-col">
                    <SectionErrorBoundary scope="admin-workbench:email" title="邮件工作台加载失败">
                      <EmailWorkbench />
                    </SectionErrorBoundary>
                  </div>
                </div>
              ) : (
                <ScrollArea className="h-full">
                  <div className="p-4 md:p-6">
                    <div className="rounded-xl bg-card border border-card-border/60 shadow-sm p-4 md:p-6 min-h-[calc(100vh-49px-2rem)]">
                      <SectionErrorBoundary scope={`admin-workbench:${activeTab}`} title="工作台加载失败">
                        {isProductEdit ? (
                          <ProductEditPage embedded productId={productId} />
                        ) : isCouponEdit ? (
                          <CouponEditPage embedded couponId={couponId} />
                        ) : (
                          <>
                            {activeTab === "home" && (
                              <ManagerWorkbench
                                onNavigate={handleTabChange}
                              />
                            )}
                            {activeTab === "create-task" && (
                              <MerchantOnboarding
                                onNavigate={handleTabChange}
                              />
                            )}
                            {activeTab === "transactions" && <FinanceTabs onNavigate={handleTabChange} />}
                            {activeTab === "products" && <ProductsTabs onNavigate={handleTabChange} />}
                            {activeTab === "marketing" && <MarketingManager onNavigate={setActiveTab} defaultTab={isCouponEdit ? "coupons" : "ai-cockpit"} />}
                            {activeTab === "aftersales" && <AfterSalesTabs onNavigate={handleTabChange} />}
                          </>
                        )}
                      </SectionErrorBoundary>
                    </div>
                  </div>
                </ScrollArea>
              )}
            </ResizablePanel>

            {/* AI助理面板 - 可拖拽调整宽度 */}
            {activeTab !== "create-task" && isAIPanelOpen && (
              <>
                <ResizableHandle withHandle />
                <ResizablePanel defaultSize={30} minSize={20} maxSize={50}>
                  <div className="h-full bg-surface border-l border-border/60 shadow-[-8px_0_24px_-12px_hsl(220_30%_10%/0.08)]">
                    <SectionErrorBoundary scope="admin-ai-assistant" title="AI 助理暂时不可用">
                      <AdminAIAssistant
                        defaultPinned={true}
                        embedded={true}
                        onNavigate={handleTabChange}
                      />
                    </SectionErrorBoundary>
                  </div>
                </ResizablePanel>
              </>
            )}
          </ResizablePanelGroup>
        </div>
      </div>
    </SidebarProvider>
  );
}