import { Outlet, Link, useLocation, useParams, useNavigate } from "react-router";
import {
  Film,
  Users,
  Sparkles,
  FolderOpen,
  Settings,
  Search,
  Bell,
  Globe,
  ChevronDown,
  BarChart3,
  Image as ImageIcon,
  FileText,
  Sliders,
  Clapperboard,
  Video,
  Bot,
  Cpu,
  LogOut,
  User,
} from "lucide-react";
import { useState, useEffect, useRef } from "react";
import { useAuthStore } from "../../stores/authStore";
import { useBalance } from "../../hooks/useUsage";
import { useProject } from "../../hooks/useProjects";
import { useTeamGroups } from "../../hooks/useTeam";
import logoImage from "../../imports/ab7d1ce5faf061d2af2b02d93e11935.png";

export function Layout() {
  const location = useLocation();
  const params = useParams();
  const navigate = useNavigate();
  const [showNotifications, setShowNotifications] = useState(false);
  const [showUserMenu, setShowUserMenu] = useState(false);
  const [currentGroupId, setCurrentGroupId] = useState<number | "">("");
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const userMenuRef = useRef<HTMLDivElement>(null);

  const { user, clearAuth } = useAuthStore();
  const { data: balance } = useBalance();
  const { data: teamGroups = [] } = useTeamGroups();

  // Close user menu on outside click
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (userMenuRef.current && !userMenuRef.current.contains(e.target as Node)) {
        setShowUserMenu(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const notifications = [
    { id: 1, type: "task", title: "项目《重生之豪门千金》第3集分镜待审核", time: "5分钟前" },
    { id: 2, type: "system", title: "系统更新：新增AI水印功能", time: "1小时前" },
    { id: 3, type: "approval", title: "张三提交的角色设定已通过审核", time: "2小时前" },
  ];

  // Check if we're in a project route
  const projectId = params.projectId;
  const isProjectRoute = projectId !== undefined;
  const { data: currentProject } = useProject(projectId ?? "");

  // Auto-collapse sidebar when in project detail routes
  useEffect(() => {
    setSidebarCollapsed(isProjectRoute);
  }, [isProjectRoute]);

  // Determine active section based on current path
  const getActiveSection = () => {
    const path = location.pathname;
    if (path.includes("/agent")) return "agent";
    if (path.includes("/storyboard")) return "storyboard";
    if (path.includes("/video")) return "video";
    if (
      path.includes("/characters") ||
      path.includes("/scenes") ||
      path.includes("/props") ||
      path.includes("/settings")
    ) {
      return "settings";
    }
    if (
      path.includes("/outline") ||
      path.includes("/episodes") ||
      path === `/project/${projectId}`
    ) {
      return "script";
    }
    return "script";
  };

  const activeSection = getActiveSection();

  const projectSections = [
    { id: "agent", label: "Agent制作", icon: Bot, path: `/project/${projectId}/agent` },
    { id: "script", label: "剧本", icon: FileText, path: `/project/${projectId}` },
    {
      id: "settings",
      label: "设定",
      icon: Sliders,
      path: `/project/${projectId}/characters`,
    },
    {
      id: "storyboard",
      label: "分镜",
      icon: Clapperboard,
      path: `/project/${projectId}/storyboard`,
    },
    { id: "video", label: "视频", icon: Video, path: `/project/${projectId}/video` },
  ];

  return (
    <div className="h-screen flex bg-background">
      {/* Left Sidebar */}
      <aside className={`border-r border-border bg-card flex flex-col transition-all duration-300 ${sidebarCollapsed ? 'w-0 overflow-hidden' : 'w-56'}`}>
        {/* Logo */}
        <div className="h-14 border-b border-border flex items-center justify-center px-4">
          <Link to="/" className="flex items-center gap-2">
            {/* ZK Logo with Film Icon */}
            <div className="relative">
              <Film className="w-8 h-8 text-primary" />
              <div className="absolute inset-0 flex items-center justify-center">
                <span className="text-[10px] font-bold text-primary">ZK</span>
              </div>
            </div>
            {/* Product Name and Version */}
            <div className="flex items-baseline gap-1">
              <span className="text-sm font-semibold text-foreground">Dramix</span>
              <span className="text-xs text-muted-foreground">V1</span>
            </div>
          </Link>
        </div>

        <nav className="flex-1 p-3 overflow-auto">
          {/* 小组板块 */}
          <div className="text-xs text-muted-foreground px-3 mb-2">小组</div>
          <div className="mb-6 px-3">
            <div className="relative">
              <select
                value={currentGroupId}
                onChange={(e) => setCurrentGroupId(Number(e.target.value) || "")}
                className="w-full px-3 py-2 rounded-lg border border-border bg-background text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20 cursor-pointer appearance-none pr-8"
              >
                <option value="">全部小组</option>
                {teamGroups.map((g) => (
                  <option key={g.id} value={g.id}>{g.name}</option>
                ))}
              </select>
              <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground pointer-events-none" />
            </div>
          </div>

          {/* 创作板块 */}
          <div className="text-xs text-muted-foreground px-3 mb-2">创作</div>
          <Link
            to="/new-project"
            className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors mb-1 ${
              location.pathname === "/new-project"
                ? "bg-accent text-accent-foreground"
                : "text-foreground hover:bg-muted"
            }`}
          >
            <Sparkles className="w-4 h-4" />
            剧本生成短剧
          </Link>

          {/* 我的板块 */}
          <div className="text-xs text-muted-foreground px-3 mt-6 mb-2">我的</div>
          <Link
            to="/"
            className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors mb-1 ${
              location.pathname === "/"
                ? "bg-accent text-accent-foreground"
                : "text-foreground hover:bg-muted"
            }`}
          >
            <FolderOpen className="w-4 h-4" />
            项目
          </Link>

          <Link
            to="/assets/character"
            className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors mb-1 ${
              location.pathname.startsWith("/assets")
                ? "bg-accent text-accent-foreground"
                : "text-foreground hover:bg-muted"
            }`}
          >
            <ImageIcon className="w-4 h-4" />
            资产
          </Link>

          {/* 企业配置 */}
          <div className="text-xs text-muted-foreground px-3 mt-6 mb-2">企业配置</div>
          <Link
            to="/team"
            className="flex items-center gap-3 px-3 py-2 rounded-lg text-sm text-foreground hover:bg-muted transition-colors mb-1"
          >
            <Users className="w-4 h-4" />
            团队管理
          </Link>
          <Link
            to="/usage"
            className="flex items-center gap-3 px-3 py-2 rounded-lg text-sm text-foreground hover:bg-muted transition-colors mb-1"
          >
            <BarChart3 className="w-4 h-4" />
            用量统计
          </Link>
          <Link
            to="/models"
            className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors mb-1 ${
              location.pathname === "/models"
                ? "bg-accent text-accent-foreground"
                : "text-foreground hover:bg-muted"
            }`}
          >
            <Cpu className="w-4 h-4" />
            模型配置
          </Link>
          <Link
            to="/settings"
            className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${
              location.pathname === "/settings"
                ? "bg-accent text-accent-foreground"
                : "text-foreground hover:bg-muted"
            }`}
          >
            <Settings className="w-4 h-4" />
            AI生成水印
          </Link>
        </nav>

        {/* Credits Display */}
        <div className="p-3 border-t border-border">
          <div className="flex items-center justify-between px-3 py-2 text-sm">
            <span className="flex items-center gap-2 text-primary">
              <Sparkles className="w-4 h-4" />
              <span className="font-medium">
                {Number(balance?.balance ?? 0).toLocaleString()}
              </span>
            </span>
            <button
              onClick={() => navigate("/usage")}
              className="text-xs text-muted-foreground hover:text-foreground"
            >
              购买
            </button>
          </div>
        </div>
      </aside>

      {/* Main Content */}
      <div className="flex-1 flex flex-col overflow-hidden">
        {/* Top Header */}
        <header className="h-14 border-b border-border bg-card flex items-center justify-between px-6">
          <div className="flex items-center gap-4 flex-1">
            {/* Logo - Show when sidebar is collapsed */}
            {sidebarCollapsed && (
              <Link to="/" className="flex-shrink-0 flex items-center gap-2">
                {/* ZK Logo with Film Icon */}
                <div className="relative">
                  <Film className="w-7 h-7 text-primary" />
                  <div className="absolute inset-0 flex items-center justify-center">
                    <span className="text-[9px] font-bold text-primary">ZK</span>
                  </div>
                </div>
                {/* Product Name and Version */}
                <div className="flex items-baseline gap-1">
                  <span className="text-sm font-semibold text-foreground">Dramix</span>
                  <span className="text-xs text-muted-foreground">V1</span>
                </div>
              </Link>
            )}

            {/* Search Bar */}
            <div className="flex-1 max-w-md">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <input
                  type="text"
                  placeholder="搜索项目或文档"
                  className="w-full pl-9 pr-4 py-1.5 rounded-lg border border-border bg-background text-sm text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
            </div>
          </div>

          {/* Right Section */}
          <div className="flex items-center gap-4">
            {/* Top Nav Menu */}
            <nav className="flex items-center gap-1 text-sm text-muted-foreground">
              <button className="px-3 py-1.5 hover:text-foreground transition-colors">工具</button>
              <button className="px-3 py-1.5 hover:text-foreground transition-colors">费用</button>
              <button className="px-3 py-1.5 hover:text-foreground transition-colors">支持</button>
              <button className="px-3 py-1.5 hover:text-foreground transition-colors">文档</button>
            </nav>

            {/* Notifications */}
            <div className="relative">
              <button
                onClick={() => setShowNotifications(!showNotifications)}
                className="relative p-2 hover:bg-muted rounded-lg transition-colors"
              >
                <Bell className="w-4 h-4 text-muted-foreground" />
                <span className="absolute top-1 right-1 w-2 h-2 bg-destructive rounded-full"></span>
              </button>

              {showNotifications && (
                <div className="absolute right-0 top-12 w-80 bg-card border border-border rounded-xl shadow-lg z-50">
                  <div className="p-4 border-b border-border">
                    <h3 className="font-medium text-foreground">通知中心</h3>
                  </div>
                  <div className="max-h-96 overflow-auto">
                    {notifications.map((notif) => (
                      <button
                        key={notif.id}
                        className="w-full p-4 text-left hover:bg-muted transition-colors border-b border-border last:border-b-0"
                      >
                        <div className="text-sm text-foreground mb-1">{notif.title}</div>
                        <div className="text-xs text-muted-foreground">{notif.time}</div>
                      </button>
                    ))}
                  </div>
                  <div className="p-3 border-t border-border text-center">
                    <button className="text-sm text-primary hover:underline">查看全部</button>
                  </div>
                </div>
              )}
            </div>

            {/* Language Switcher */}
            <button className="p-2 hover:bg-muted rounded-lg transition-colors">
              <Globe className="w-4 h-4 text-muted-foreground" />
            </button>

            {/* User Avatar */}
            <div className="relative" ref={userMenuRef}>
              <button
                onClick={() => setShowUserMenu(!showUserMenu)}
                className="flex items-center gap-2 px-2 py-1.5 hover:bg-muted rounded-lg transition-colors"
              >
                <div className="w-7 h-7 rounded-full bg-gradient-to-br from-[#5b5ff9] to-[#8b5ff9] flex items-center justify-center">
                  <span className="text-[11px] font-bold text-white">
                    {user?.username?.[0]?.toUpperCase() ?? "U"}
                  </span>
                </div>
                <ChevronDown className="w-3 h-3 text-muted-foreground" />
              </button>
              {showUserMenu && (
                <div className="absolute right-0 top-12 w-48 bg-card border border-border rounded-xl shadow-lg z-50">
                  <div className="px-4 py-3 border-b border-border">
                    <div className="flex items-center gap-2">
                      <User className="w-4 h-4 text-muted-foreground" />
                      <span className="text-sm font-medium text-foreground truncate">{user?.username}</span>
                    </div>
                  </div>
                  <button
                    onClick={() => { clearAuth(); navigate("/login"); }}
                    className="w-full flex items-center gap-2 px-4 py-2.5 text-sm text-destructive hover:bg-muted transition-colors rounded-b-xl"
                  >
                    <LogOut className="w-4 h-4" />
                    退出登录
                  </button>
                </div>
              )}
            </div>
          </div>
        </header>

        {/* Project Navigation */}
        {isProjectRoute && (
          <div className="border-b border-border bg-card px-6 py-3">
            <div className="flex items-center gap-6">
              {/* Project Name */}
              <div className="flex items-center gap-2 pr-6 border-r border-border">
                <Film className="w-4 h-4 text-primary" />
                <span className="font-medium text-foreground">{currentProject?.name ?? projectId}</span>
              </div>

              {/* Section Tabs */}
              <div className="flex items-center gap-2">
                {projectSections.map((section) => {
                  const Icon = section.icon;
                  return (
                    <button
                      key={section.id}
                      onClick={() => navigate(section.path)}
                      className={`flex items-center gap-2 px-4 py-1.5 rounded-lg text-sm transition-all ${
                        activeSection === section.id
                          ? "bg-accent text-accent-foreground font-medium"
                          : "text-muted-foreground hover:text-foreground hover:bg-muted"
                      }`}
                    >
                      <Icon className="w-4 h-4" />
                      {section.label}
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
        )}

        {/* Page Content */}
        <main className="flex-1 overflow-auto">
          <Outlet />
        </main>
      </div>
    </div>
  );
}