"use client";

import React from "react";
import { gql } from "@apollo/client";
import { useQuery } from "@apollo/experimental-nextjs-app-support/ssr";
import { 
  LogOut, 
  Compass, 
  Swords, 
  MessageSquare, 
  Bookmark, 
  User, 
  CreditCard, 
  Settings,
  Search,
} from "lucide-react";
import { useRouter, usePathname } from "next/navigation";
import Link from "next/link";
import Image from "next/image";

interface MyProfileData {
  me: {
    id: string;
    email: string;
    name: string;
    handle: string | null;
    avatar: string | null;
  } | null;
}

const GET_MY_PROFILE = gql`
  query GetMyProfile {
    me {
      id
      email
      name
      handle
      avatar
    }
  }
`;

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const router = useRouter();
  const { loading, error, data } = useQuery<MyProfileData>(GET_MY_PROFILE);

  console.log("GraphQL Data:", data);
  console.log("GraphQL Error:", error);

  const menuItems = [
    { name: "Discover", href: "/", icon: Compass },
    { name: "Roleplay", href: "/roleplay", icon: Swords },
    { name: "Messages", href: "/messages", icon: MessageSquare },
    { name: "Library", href: "/library", icon: Bookmark },
    { name: "Profile", href: "/profile", icon: User },
    { name: "Subscription", href: "/subscription", icon: CreditCard },
    { name: "Settings", href: "/settings", icon: Settings },
  ];

  return (
    <div className="flex h-screen flex-col bg-gray-50 text-gray-900">
      
      {/* --- 1. 顶部 Header (贯穿式) --- */}
      <header className="h-16 bg-white border-b border-gray-200 flex items-center justify-between px-6 shrink-0 z-20">
        <div className="flex items-center gap-8">
          {/* Logo 区域 */}
          <Link href="/" className="flex items-center gap-2">
            <div className="w-8 h-8 bg-linear-to-br from-pink-600 to-purple-600 rounded-lg flex items-center justify-center text-white font-bold text-xs shadow-sm">
              RP
            </div>
            <span className="font-bold text-xl tracking-tight">RoleplayAI</span>
          </Link>

          {/* 模拟搜索框 (对应图中右上角风格) */}
          <div className="hidden md:flex items-center gap-2 bg-gray-100 px-4 py-2 rounded-full w-80">
            <Search className="w-4 h-4 text-gray-400" />
            <input 
              type="text" 
              placeholder="Search by tag..." 
              className="bg-transparent text-sm outline-none w-full"
            />
          </div>
        </div>

        {/* Header 右侧 */}
        <div className="flex items-center gap-4">
          {/* 积分显示 */}
          <div className="flex items-center gap-2 bg-purple-50 px-3 py-1.5 rounded-full border border-purple-100">
            <span className="text-sm">🪙</span>
            <span className="text-sm font-bold text-purple-700">200</span> 
          </div>

          {/* 真实头像逻辑 */}
          <div className="flex items-center gap-3 ml-2">
            {loading ? (
              <div className="w-8 h-8 bg-gray-200 animate-pulse rounded-full" />
            ) : data?.me ? (
              <div className="flex items-center gap-3">
                <div className="text-right hidden lg:block">
                  <p className="text-xs font-bold text-gray-900 leading-none">{data.me.name}</p>
                  <p className="text-[10px] text-gray-500 leading-none mt-1">@{data.me.handle || 'user'}</p>
                </div>
                <div className="w-9 h-9 rounded-full bg-linear-to-tr from-purple-100 to-pink-100 border border-purple-200 overflow-hidden relative">
                  {data.me.avatar ? (
                    <Image src={data.me.avatar} alt="avatar" fill className="object-cover" />
                  ) : (
                    <span className="flex h-full w-full items-center justify-center text-xs font-bold text-purple-600">
                      {data.me.name?.charAt(0).toUpperCase()}
                    </span>
                  )}
                </div>
              </div>
            ) : (
              <Link href="/login" className="text-xs font-bold text-pink-600 hover:underline">Login</Link>
            )}
          </div>
        </div>
      </header>

      {/* --- 下半部分主体 --- */}
      <div className="flex flex-1 overflow-hidden">
        
        {/* --- 2. 左侧 Sidebar --- */}
        <aside className="w-64 bg-white border-r border-gray-200 flex flex-col shrink-0 z-10">
          <nav className="flex-1 p-4 space-y-1 overflow-y-auto">
            {menuItems.map((item) => {
              const isActive = pathname === item.href;
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  className={`flex items-center gap-3 px-4 py-3 rounded-xl font-medium text-sm transition-all ${
                    isActive 
                      ? "bg-gray-900 text-white shadow-md" 
                      : "text-gray-500 hover:bg-gray-100 hover:text-gray-900"
                  }`}
                >
                  <item.icon className={`w-5 h-5 ${isActive ? "text-white" : "text-gray-400"}`} />
                  {item.name}
                  {item.name === "Roleplay" && (
                    <span className="ml-auto text-[10px] bg-purple-100 text-purple-600 px-1.5 py-0.5 rounded font-bold uppercase">Free</span>
                  )}
                </Link>
              );
            })}
          </nav>

          {/* 底部退出按钮 (更简洁) */}
          <div className="p-4 border-t border-gray-100">
            <button 
              onClick={() => {/* handleLogout logic */}}
              className="flex items-center gap-3 w-full px-4 py-3 text-sm font-medium text-gray-500 hover:text-red-600 hover:bg-red-50 rounded-xl transition-colors"
            >
              <LogOut className="w-5 h-5" />
              Logout
            </button>
          </div>
        </aside>

        {/* --- 3. 右侧 Main Content --- */}
        <main className="flex-1 overflow-y-auto bg-[#fafafa]">
          {/* 这里可以放置页面内局部的二级分类 Header (比如 Discover 里的 All, Fantasy 等) */}
          <div className="min-h-full">
            {children}
          </div>
        </main>

      </div>
    </div>
  );
}