"use client";

import { usePathname } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import { Home, FolderOpen, LayoutGrid, Settings, Sparkles, AtSign, ShieldCheck, LogOut, Link2, FileText, Activity, Wrench } from "lucide-react";
import Link from "next/link";
import { cn } from "@/lib/utils";
import { useCreditBalance, useCurrentUser } from "@/hooks/use-api";
import { NotificationsDropdown } from "./notifications-dropdown";
import { signOut } from "next-auth/react";

const navItems = [
  { href: "/dashboard", icon: Home, label: "Ana Sayfa" },
  { href: "/dashboard/create-project", icon: Sparkles, label: "Yeni Proje Üret" },
  { href: "/dashboard/projects", icon: FolderOpen, label: "Projeler" },
  { href: "/dashboard/render-queue", icon: Activity, label: "Render Monitör" },
  { href: "/dashboard/templates", icon: LayoutGrid, label: "Şablonlar" },
  { href: "/dashboard/tools", icon: Wrench, label: "Araçlar" },
  { href: "/dashboard/settings", icon: Settings, label: "Ayarlar" },
];

const adminNavItem = { href: "/dashboard/admin", icon: ShieldCheck, label: "Admin Panel" };

export function MobileNav() {
  const pathname = usePathname();
  const localePath = pathname.replace(/^\/[a-z]{2}/, "");

  return (
    <nav className="mobile-nav md:hidden">
      <div className="flex items-center justify-around px-2">
        {navItems.map((item) => {
          const isActive =
            localePath === item.href ||
            (item.href !== "/dashboard" && localePath.startsWith(item.href));
          const Icon = item.icon;

          return (
            <Link
              key={item.href}
              href={item.href}
              className={cn(
                "relative flex flex-col items-center gap-1 py-2 px-3 rounded-xl min-w-[4.5rem] transition-colors",
                isActive
                  ? "text-white"
                  : "text-[var(--color-text-muted)] active:text-[var(--color-text-primary)]"
              )}
            >
              <div className="relative">
                <Icon size={24} strokeWidth={isActive ? 2.5 : 1.8} />
                {isActive && (
                  <motion.div
                    layoutId="nav-indicator"
                    className="absolute -inset-2 rounded-xl bg-white/10"
                    transition={{ type: "spring", bounce: 0.2, duration: 0.5 }}
                  />
                )}
              </div>
              <span className="text-xs font-semibold tracking-wide mt-1">
                {item.label}
              </span>
            </Link>
          );
        })}
      </div>
    </nav>
  );
}

function CreditCard() {
  const { data, isLoading } = useCreditBalance();

  // Axios interceptor unwrap sonrası data doğrudan backend yanıtı
  const creditData = data as any;
  const isAdmin = creditData?.isAdmin === true;
  const remaining = creditData?.remaining ?? creditData?.balance ?? 0;
  const total = creditData?.total ?? creditData?.monthlyLimit ?? 50;
  const planName = creditData?.plan ?? "Free";
  const pct = isAdmin ? 100 : (total > 0 ? Math.round((remaining / total) * 100) : 0);

  return (
    <div className="mx-4 mb-6 p-5 rounded-2xl bg-[var(--color-bg-elevated)] border border-[var(--color-border-faint)] shadow-sm">
      <div className="flex items-center justify-between mb-3">
        <span className="text-sm font-medium text-[var(--color-text-muted)]">Kalan Kredi</span>
        <span className="badge bg-white/10 text-white border border-white/20">{planName}</span>
      </div>
      <div className="text-3xl font-bold font-[family-name:var(--font-display)] text-[var(--color-text-primary)]">
        {isLoading ? "..." : isAdmin ? "∞" : remaining}
      </div>
      <div className="progress-bar mt-2">
        <div
          className="progress-bar-fill"
          style={{ width: `${pct}%` }}
        />
      </div>
      <p className="text-xs text-[var(--color-text-ghost)] mt-2">
        {isAdmin ? "Sınırsız admin erişimi" : `${total} kredilik planınızın ${remaining}'${remaining === 1 ? "i" : "si"} kaldı`}
      </p>
    </div>
  );
}

export function DesktopSidebar() {
  const pathname = usePathname();
  const localePath = pathname.replace(/^\/[a-z]{2}/, "");
  const { data } = useCurrentUser();
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const user = (data as any)?.data ?? data;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const roles: string[] = (user?.roles ?? []).map((r: any) => typeof r === "string" ? r : (r?.role?.name ?? r?.name ?? ""));
  const isAdmin = roles.includes("admin") || roles.includes("superadmin");

  const handleLogout = () => {
    signOut({ redirect: true, callbackUrl: "/signin" });
  };

  return (
    <aside className="hidden md:flex md:w-72 lg:w-80 flex-col h-screen sticky top-0 border-r border-[var(--color-border-faint)] bg-[var(--color-bg-deep)]">
      {/* Logo */}
      <div className="flex items-center gap-4 px-8 py-6 border-b border-[var(--color-border-faint)]">
        <div className="w-10 h-10 rounded-xl bg-white flex items-center justify-center shadow-md">
          <Sparkles size={20} className="text-black" />
        </div>
        <div>
          <h1 className="font-[family-name:var(--font-display)] text-xl font-bold tracking-tight text-[var(--color-text-primary)]">
            ContentGen
          </h1>
          <p className="text-xs font-semibold text-[var(--color-text-muted)] uppercase tracking-[0.2em]">
            AI Studio
          </p>
        </div>
      </div>

      {/* Navigation */}
      <nav className="flex-1 px-4 py-6 space-y-1.5">
        {navItems.map((item) => {
          const isActive =
            localePath === item.href ||
            (item.href !== "/dashboard" && localePath.startsWith(item.href));
          const Icon = item.icon;

          return (
            <Link
              key={item.href}
              href={item.href}
              className={cn(
                "relative flex items-center gap-4 px-4 py-3 rounded-xl text-base font-semibold transition-all duration-200",
                isActive
                  ? "text-white bg-white/5"
                  : "text-[var(--color-text-muted)] hover:text-white hover:bg-[var(--color-bg-surface)]"
              )}
            >
              {isActive && (
                <motion.div
                  layoutId="sidebar-active"
                  className="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 rounded-r-full bg-white"
                  transition={{ type: "spring", bounce: 0.2, duration: 0.5 }}
                />
              )}
              <Icon size={20} strokeWidth={isActive ? 2.5 : 2} />
              <span>{item.label}</span>
            </Link>
          );
        })}
      </nav>

      {/* Credits Card */}
      <CreditCard />

      {/* Admin Panel Linki (sadece admin) */}
      {isAdmin && (
        <div className="px-4 pb-4">
          <Link
            href={adminNavItem.href}
            className={cn(
              "relative flex items-center gap-4 px-4 py-3 rounded-xl text-base font-semibold transition-all duration-200",
              localePath.startsWith("/dashboard/admin")
                ? "text-white bg-white/10"
                : "text-[var(--color-text-ghost)] hover:text-white hover:bg-white/5"
            )}
          >
            <ShieldCheck size={20} strokeWidth={2} />
            <span>{adminNavItem.label}</span>
          </Link>
        </div>
      )}

      {/* Çıkış Butonu */}
      <div className="px-4 pb-6">
        <button
          onClick={handleLogout}
          className="w-full flex items-center gap-4 px-4 py-3 rounded-xl text-base font-semibold text-[var(--color-text-ghost)] hover:text-white hover:bg-white/5 transition-all duration-200"
        >
          <LogOut size={20} strokeWidth={2} />
          <span>Çıkış Yap</span>
        </button>
      </div>
    </aside>
  );
}

function UserAvatar() {
  const { data } = useCurrentUser();
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const user = (data as any)?.data ?? data;
  const initial = user?.firstName?.[0] ?? user?.email?.[0]?.toUpperCase() ?? "U";

  return (
    <button
      className="w-10 h-10 rounded-full bg-white flex items-center justify-center text-black text-sm font-bold shadow-sm border border-white/20"
      aria-label="Profil"
    >
      {initial}
    </button>
  );
}

export function TopBar() {
  return (
    <header className="sticky top-0 z-40 glass">
      <div className="flex items-center justify-between px-4 md:px-6 h-14 md:h-16">
        {/* Mobil logo */}
        <div className="flex items-center gap-3 md:hidden">
          <div className="w-8 h-8 rounded-lg bg-white flex items-center justify-center">
            <Sparkles size={16} className="text-black" />
          </div>
          <span className="font-[family-name:var(--font-display)] font-bold text-lg">
            ContentGen
          </span>
        </div>

        {/* Spacer — desktop */}
        <div className="hidden md:block" />

        {/* Sağ taraf */}
        <div className="flex items-center gap-3">
          {/* Bildirimler — interaktif dropdown */}
          <NotificationsDropdown />

          {/* Avatar */}
          <UserAvatar />
        </div>
      </div>
    </header>
  );
}

export function AppShell({ children }: { children: React.ReactNode }) {
  return (
    <div className="flex min-h-screen">
      <DesktopSidebar />
      <div className="flex-1 flex flex-col min-h-screen">
        <TopBar />
        <main className="flex-1 px-[var(--spacing-page)] py-5 pb-safe page-enter">
          {children}
        </main>
        <MobileNav />
      </div>
    </div>
  );
}

