"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";
import { usePathname } from "next/navigation";
import {
  LayoutDashboard,
  FileSpreadsheet,
  Settings,
  ChevronRight,
  X,
  Shield,
  Sparkles,
  FolderKanban,
  Lock,
} from "lucide-react";
import { useI18n } from "@/lib/i18n/context";
import { useDashboardShell } from "./DashboardShellContext";
import { apiFetch } from "@/lib/csrf/client";

export interface NavItemConfig {
  labelDe: string;
  labelEn: string;
  href: string;
  icon: React.ComponentType<{ className?: string }>;
  /** Gated behind an active Pro plan — free users see a lock and get the paywall instead of navigating. */
  proOnly?: boolean;
}

export const DASHBOARD_NAV_ITEMS: NavItemConfig[] = [
  {
    labelDe: "ÜBERSICHT",
    labelEn: "OVERVIEW",
    href: "/dashboard",
    icon: LayoutDashboard,
  },
  {
    labelDe: "PROJEKTE",
    labelEn: "PROJECTS",
    href: "/dashboard/projects",
    icon: FolderKanban,
    proOnly: true,
  },

  {
    labelDe: "EXPORT",
    labelEn: "EXPORT",
    href: "/dashboard/export",
    icon: FileSpreadsheet,
  },
  {
    labelDe: "PREISE",
    labelEn: "PRICING",
    href: "/dashboard/pricing",
    icon: Sparkles,
  },
  {
    labelDe: "EINSTELLUNGEN",
    labelEn: "ACCOUNT",
    href: "/dashboard/settings",
    icon: Settings,
  },
];

export function Sidebar() {
  const pathname = usePathname();
  const { language } = useI18n();
  const isDe = language === "de";
  const { isMobileDrawerOpen, closeMobileDrawer } = useDashboardShell();
  const [user, setUser] = useState<{
    name?: string | null;
    email?: string | null;
  } | null>(null);
  const [isPro, setIsPro] = useState(false);

  useEffect(() => {
    let active = true;
    apiFetch("/api/auth/session")
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => {
        if (active && data?.user) {
          setUser(data.user);
          setIsPro(Boolean(data.user.isPro));
        }
      })
      .catch(() => {});
    return () => {
      active = false;
    };
  }, []);

  const displayName = user?.name || user?.email || (isDe ? "Konto" : "Account");
  const initials = (user?.name || user?.email || "AC")
    .split(/\s+/)
    .map((part) => part[0] ?? "")
    .join("")
    .slice(0, 2)
    .toUpperCase();

  // Helper to render navigation items list
  const renderNavLinks = (onItemClick?: () => void) => (
    <nav
      className="p-4 space-y-1.5 font-mono text-xs uppercase tracking-caps"
      aria-label="Sidebar Navigation"
    >
      {DASHBOARD_NAV_ITEMS.map((item) => {
        const Icon = item.icon;
        const isActive =
          item.href === "/dashboard"
            ? pathname === "/dashboard"
            : pathname.startsWith(item.href);
        // Pro-only items stay fully navigable — the page itself explains what's
        // behind the paywall. Only the free-vs-pro badge changes here.
        const showProHint = Boolean(item.proOnly) && !isPro;

        return (
          <Link
            key={item.href}
            href={item.href}
            onClick={onItemClick}
            aria-current={isActive ? "page" : undefined}
            className={`flex items-center justify-between px-4 py-3 transition-colors ${
              isActive
                ? "bg-black text-white font-semibold shadow-sm"
                : "text-[#475569] hover:bg-[#F8FAFC] hover:text-black"
            }`}
          >
            <div className="flex items-center gap-3">
              <Icon className={`w-4 h-4 ${isActive ? "text-white" : "text-[#64748B]"}`} />
              <span>{isDe ? item.labelDe : item.labelEn}</span>
            </div>
            {showProHint ? (
              <span
                className={`flex items-center gap-1 text-[9px] font-bold ${
                  isActive ? "text-white/80" : "text-[#94A3B8]"
                }`}
              >
                <Lock className="w-3 h-3" />
                PRO
              </span>
            ) : (
              isActive && <ChevronRight className="w-3.5 h-3.5 text-white" />
            )}
          </Link>
        );
      })}
    </nav>
  );

  // Helper to render legal navigation links
  const renderLegalLinksSection = (onItemClick?: () => void) => (
    <div className="px-4 py-2.5 border-t border-[#E2E8F0] bg-[#F8FAFC] flex items-center justify-between font-mono text-[10px] text-[#64748B]">
      <Link
        href="/disclaimer"
        onClick={onItemClick}
        className="hover:text-black hover:underline transition-colors"
      >
        {isDe ? "Disclaimer" : "Legal"}
      </Link>
      <span className="text-[#CBD5E1]">•</span>
      <Link
        href="/privacy"
        onClick={onItemClick}
        className="hover:text-black hover:underline transition-colors"
      >
        {isDe ? "Datenschutz" : "Privacy"}
      </Link>
      <span className="text-[#CBD5E1]">•</span>
      <Link
        href="/terms"
        onClick={onItemClick}
        className="hover:text-black hover:underline transition-colors"
      >
        {isDe ? "AGB" : "Terms"}
      </Link>
    </div>
  );

  // Helper to render profile footer
  const renderProfileFooter = (onProfileClick?: () => void) => (
    <div className="p-4 border-t border-[#E2E8F0] bg-white">
      <Link
        href="/dashboard/settings"
        onClick={onProfileClick}
        className="flex items-center gap-3 p-2 hover:bg-[#F8FAFC] transition-colors"
      >
        <div className="w-9 h-9 bg-[#1E293B] text-white flex items-center justify-center font-mono text-xs font-bold shrink-0 border border-black">
          {initials}
        </div>
        <div className="flex flex-col min-w-0 flex-1">
          <span className="font-sans font-semibold text-xs text-black truncate">
            {displayName}
          </span>
          <span className="font-mono text-[10px] text-[#64748B] truncate">
            {user?.email || (isDe ? "Nicht angemeldet" : "Signed out")}
          </span>
        </div>
      </Link>
    </div>
  );

  return (
    <>
      {/* ------------------------------------------------------------- */}
      {/* 1. Desktop Static Sidebar (Visible on >= 768px)               */}
      {/* ------------------------------------------------------------- */}
      <aside
        data-testid="desktop-sidebar"
        className="hidden md:flex w-64 bg-white border-r border-[#E2E8F0] flex-col justify-between shrink-0 font-sans min-h-screen sticky top-0 h-screen overflow-y-auto"
        aria-label="Desktop Navigation"
      >
        {/* Top Section */}
        <div className="flex flex-col flex-1">
          {/* Brand Header */}
          <div className="h-20 px-5 border-b border-[#E2E8F0] flex items-center justify-between shrink-0 bg-white">
            <Link href="/" className="flex items-center gap-3 group">
              <div className="w-12 h-12 bg-white border-2 border-black p-1 shadow-xs overflow-hidden flex items-center justify-center shrink-0 transition-transform group-hover:scale-95">
                <Image
                  src="/icon.png"
                  alt="ScanReceipts Logo"
                  width={48}
                  height={48}
                  className="w-full h-full object-contain"
                  priority
                />
              </div>
              <div className="flex flex-col justify-center">
                <span className="font-display font-black text-base tracking-tight text-black leading-tight whitespace-nowrap">
                  SCAN RECEIPTS
                </span>
              </div>
            </Link>
          </div>

          {/* Navigation Links */}
          <div className="flex-1 py-2">
            {renderNavLinks()}
          </div>
        </div>

        {/* Bottom Section: Legal Links & Profile */}
        <div className="shrink-0">
          {renderLegalLinksSection()}
          {renderProfileFooter()}
        </div>
      </aside>

      {/* ------------------------------------------------------------- */}
      {/* 2. Mobile Slide-Out Drawer (Visible on < 768px)               */}
      {/* ------------------------------------------------------------- */}
      <div
        data-testid="mobile-drawer-root"
        className={`fixed inset-0 z-50 md:hidden transition-all duration-300 ${
          isMobileDrawerOpen ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0"
        }`}
        aria-hidden={!isMobileDrawerOpen}
      >
        {/* Backdrop overlay */}
        <div
          data-testid="mobile-drawer-backdrop"
          onClick={closeMobileDrawer}
          className={`fixed inset-0 bg-black/60 backdrop-blur-sm transition-opacity duration-300 ${
            isMobileDrawerOpen ? "opacity-100" : "opacity-0"
          }`}
          aria-hidden="true"
        />

        {/* Slide-out Drawer Panel */}
        <aside
          role="dialog"
          aria-modal="true"
          aria-label="Navigation drawer"
          data-testid="mobile-drawer-panel"
          className={`fixed inset-y-0 left-0 w-72 max-w-[85vw] bg-white border-r border-[#E2E8F0] flex flex-col justify-between shadow-2xl transition-transform duration-300 ease-in-out font-sans z-50 h-full overflow-y-auto ${
            isMobileDrawerOpen ? "translate-x-0" : "-translate-x-full"
          }`}
        >
          <div className="flex flex-col flex-1">
            {/* Drawer Header with Brand & Close Button */}
            <div className="h-20 px-5 border-b border-[#E2E8F0] flex items-center justify-between shrink-0 bg-white">
              <Link
                href="/"
                onClick={closeMobileDrawer}
                className="flex items-center gap-3.5 group"
              >
                <div className="w-12 h-12 bg-white border-2 border-black p-1 shadow-xs overflow-hidden flex items-center justify-center shrink-0">
                  <Image
                    src="/icon.png"
                    alt="ScanReceipts Logo"
                    width={48}
                    height={48}
                    className="w-full h-full object-contain"
                    priority
                  />
                </div>
                <div className="flex flex-col justify-center">
                  <span className="font-display font-black text-base tracking-tight text-black leading-tight whitespace-nowrap">
                    SCAN RECEIPTS
                  </span>
                </div>
              </Link>

              {/* Close Button */}
              <button
                type="button"
                data-testid="mobile-drawer-close"
                onClick={closeMobileDrawer}
                className="p-2 border border-[#E2E8F0] hover:border-black text-black transition-colors"
                aria-label="Close navigation"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            {/* Navigation Links */}
            <div className="flex-1 py-2">
              {renderNavLinks(closeMobileDrawer)}
            </div>
          </div>

          {/* Bottom Section: Legal Links & Profile */}
          <div className="shrink-0">
            {renderLegalLinksSection(closeMobileDrawer)}
            {renderProfileFooter(closeMobileDrawer)}
          </div>
        </aside>
      </div>
    </>
  );
}
