"use client";
import React from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
  LayoutDashboard, Users, Calendar, MessageSquare, Settings,
  Smartphone, LogOut, Stethoscope, Zap, ChevronRight, Sparkles,
  Menu, X, Bot, TreePine, Workflow, FlaskConical, CalendarDays, UserPlus,
} from "lucide-react";
import { useRef, useState, useEffect } from "react";

interface ClinicSession { id: string; name: string; wahaStatus: string; }

interface NavItem {
  href: string;
  label: string;
  icon: React.ComponentType<any>;
  isNew?: boolean;
}

const nav: NavItem[] = [
  { href: "/dashboard", label: "Dashboard", icon: LayoutDashboard },
  { href: "/appointments", label: "Appointments", icon: Calendar },
  { href: "/calendar", label: "Calendar", icon: CalendarDays },
  { href: "/leads", label: "Leads", icon: Users },
  { href: "/treatments", label: "Treatments", icon: Stethoscope },
  { href: "/messages", label: "Messages", icon: MessageSquare },
  { href: "/chatbot-canvas", label: "Chatbot Canvas", icon: Workflow, isNew: true },
  { href: "/admin/reminder-trees", label: "Reminder Trees", icon: TreePine },
  { href: "/test-reminders", label: "Test Reminders", icon: FlaskConical },
  { href: "/connect", label: "WhatsApp", icon: Smartphone },
  { href: "/staff", label: "Staff", icon: UserPlus },
  { href: "/settings", label: "Settings", icon: Settings },
];

// Bottom nav — only show the 5 most important on mobile
const mobileNav: NavItem[] = [
  { href: "/dashboard", label: "Home", icon: LayoutDashboard },
  { href: "/appointments", label: "Book", icon: Calendar },
  { href: "/chatbot-canvas", label: "Canvas", icon: Workflow },
  { href: "/messages", label: "Msgs", icon: MessageSquare },
  { href: "/settings", label: "More", icon: Menu },
];

export default function Sidebar({ clinic }: { clinic: ClinicSession }) {
  const pathname = usePathname();
  const router = useRouter();
  const navRef = useRef<HTMLElement>(null);
  const [indicatorStyle, setIndicatorStyle] = useState({ top: 0, height: 0 });
  const [mobileOpen, setMobileOpen] = useState(false);

  const handleLogout = async () => { await fetch("/api/auth/logout", { method: "POST" }); router.push("/login"); };
  const connected = clinic.wahaStatus === "connected";

  // Close mobile drawer on route change
  useEffect(() => { setMobileOpen(false); }, [pathname]);

  // Sliding indicator for desktop
  useEffect(() => {
    if (!navRef.current) return;
    const activeIndex = nav.findIndex(item => 
      pathname === item.href || 
      (item.href !== "/" && pathname.startsWith(item.href))
    );
    if (activeIndex === -1) return;
    const links = navRef.current.querySelectorAll("a");
    const activeLink = links[activeIndex] as HTMLElement;
    if (activeLink) {
      const navRect = navRef.current.getBoundingClientRect();
      const linkRect = activeLink.getBoundingClientRect();
      setIndicatorStyle({ top: linkRect.top - navRect.top, height: linkRect.height });
    }
  }, [pathname]);

  // Prevent body scroll when drawer open
  useEffect(() => {
    if (mobileOpen) document.body.style.overflow = "hidden";
    else document.body.style.overflow = "";
    return () => { document.body.style.overflow = ""; };
  }, [mobileOpen]);

  return (
    <>
      {/* ═══════════════════════════════════════════════ */}
      {/*          DESKTOP SIDEBAR (lg+)                  */}
      {/* ═══════════════════════════════════════════════ */}
      <aside className="hidden lg:flex w-[250px] sidebar-bg flex-col h-full shrink-0 relative overflow-hidden">
        {/* Animated orb effects */}
        <div className="absolute top-0 left-0 w-[300px] h-[300px] bg-primary-600/[0.07] rounded-full blur-[80px] -translate-x-1/2 -translate-y-1/2 animate-float" />
        <div className="absolute bottom-20 right-0 w-[200px] h-[200px] bg-accent-500/[0.05] rounded-full blur-[60px] translate-x-1/2 animate-float" style={{ animationDelay: "1.5s" }} />

        {/* Brand */}
        <div className="relative px-5 py-5">
          <Link href="/dashboard" className="flex items-center gap-3 group">
            <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-primary-500 to-accent-500 flex items-center justify-center shadow-lg shadow-primary-500/30 group-hover:shadow-primary-500/50 transition-all group-hover:scale-105">
              <span className="text-white font-bold text-base">C</span>
            </div>
            <div className="flex flex-col">
              <span className="text-[16px] font-extrabold text-white tracking-tight leading-none">CLINERA</span>
              <span className="text-[8px] text-primary-400/60 font-semibold tracking-[0.2em] uppercase mt-0.5">Smart Reminders</span>
            </div>
          </Link>
        </div>

        {/* WhatsApp status */}
        <div className="relative px-4 pb-3">
          <Link href="/connect" className={`flex items-center gap-2.5 px-3 py-2.5 rounded-xl transition-all group ${
            connected
              ? "bg-emerald-500/10 border border-emerald-400/20 hover:bg-emerald-500/15 hover:border-emerald-400/30"
              : "bg-red-500/10 border border-red-400/20 hover:bg-red-500/15"
          }`}>
            <div className="relative">
              <div className={`w-2.5 h-2.5 rounded-full ${connected ? "bg-emerald-400" : "bg-red-400"}`} />
              {connected && (
                <>
                  <div className="absolute inset-0 w-2.5 h-2.5 rounded-full bg-emerald-400 animate-ping opacity-75" />
                  <div className="absolute -inset-1 rounded-full bg-emerald-400/20 animate-pulse-soft" />
                </>
              )}
            </div>
            <span className={`text-xs font-semibold ${connected ? "text-emerald-400" : "text-red-400"}`}>
              {connected ? "WhatsApp Live" : "Disconnected"}
            </span>
            <ChevronRight size={12} className={`ml-auto transition-transform group-hover:translate-x-0.5 ${connected ? "text-emerald-500/40" : "text-red-500/40"}`} />
          </Link>
        </div>

        <div className="relative mx-5 mb-2"><div className="h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent" /></div>

        {/* Navigation */}
        <nav ref={navRef} className="relative flex-1 px-3 py-1 space-y-0.5">
          <p className="text-[8px] font-bold text-primary-400/30 uppercase tracking-[0.2em] px-3 mb-2.5">Navigation</p>
          <div
            className="sidebar-indicator absolute left-3 right-3 rounded-xl bg-gradient-to-r from-primary-600/20 to-primary-600/5 pointer-events-none z-0"
            style={{ top: indicatorStyle.top, height: indicatorStyle.height, opacity: indicatorStyle.height ? 1 : 0 }}
          >
            <div className="absolute left-0 top-1/2 -translate-y-1/2 w-[3px] h-5 bg-gradient-to-b from-primary-400 to-accent-400 rounded-r-full" />
            <div className="absolute inset-0 rounded-xl bg-primary-400/[0.05] animate-pulse-soft" style={{ animationDuration: "3s" }} />
          </div>
          {nav.map(item => {
            const active = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href));
            return (
              <Link key={item.href} href={item.href}
                className={`flex items-center gap-2.5 px-3 py-2.5 rounded-xl text-[13px] font-medium transition-all relative group z-10 ${
                  active ? "text-white" : "text-white/40 hover:bg-white/[0.04] hover:text-white/70"
                }`}>
                <item.icon size={16} strokeWidth={active ? 2.2 : 1.6}
                  className={`relative transition-all ${active ? "text-primary-400" : "text-white/30 group-hover:text-white/50"}`} />
                <span className="relative flex items-center gap-1.5">
                  {item.label}
                  {item.isNew && (
                    <span className="px-1.5 py-0.5 text-[8px] font-bold bg-gradient-to-r from-emerald-500 to-cyan-500 text-white rounded-full uppercase tracking-wide animate-pulse">
                      NEW
                    </span>
                  )}
                </span>
                {item.isNew && !active && (
                  <div className="absolute -top-1 -right-1 w-2 h-2 bg-gradient-to-r from-emerald-400 to-cyan-400 rounded-full animate-ping" />
                )}
              </Link>
            );
          })}
        </nav>

        {/* Footer */}
        <div className="relative px-4 py-4 border-t border-white/[0.04]">
          <div className="flex items-center gap-2.5 px-2 py-1.5 mb-2">
            <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-primary-500/20 to-accent-500/20 border border-white/10 flex items-center justify-center">
              <span className="text-primary-300 text-xs font-bold">{clinic.name.charAt(0).toUpperCase()}</span>
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-xs font-semibold text-white/80 truncate">{clinic.name}</p>
              <p className="text-[9px] text-white/25 font-medium">Free Plan</p>
            </div>
            <Sparkles size={12} className="text-warm-400/40" />
          </div>
          <button onClick={handleLogout}
            className="flex items-center gap-2 px-3 py-1.5 w-full text-[11px] text-white/25 hover:text-red-400 hover:bg-red-500/10 rounded-lg transition-all">
            <LogOut size={13} /> Sign out
          </button>
        </div>
      </aside>

      {/* ═══════════════════════════════════════════════ */}
      {/*   MOBILE TOP HEADER BAR (< lg)                  */}
      {/* ═══════════════════════════════════════════════ */}
      <div className="lg:hidden fixed top-0 left-0 right-0 z-40 sidebar-bg px-4 py-3 flex items-center justify-between safe-area-top">
        <Link href="/dashboard" className="flex items-center gap-2.5">
          <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-primary-500 to-accent-500 flex items-center justify-center">
            <span className="text-white font-bold text-sm">C</span>
          </div>
          <span className="text-sm font-extrabold text-white tracking-tight">CLINERA</span>
        </Link>
        <div className="flex items-center gap-3">
          {/* WhatsApp status dot */}
          <Link href="/connect" className="relative">
            <Smartphone size={18} className={connected ? "text-emerald-400" : "text-red-400"} />
            <div className={`absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full ${connected ? "bg-emerald-400" : "bg-red-400"}`} />
          </Link>
          <button onClick={() => setMobileOpen(true)} className="text-white/60 hover:text-white p-1">
            <Menu size={22} />
          </button>
        </div>
      </div>

      {/* ═══════════════════════════════════════════════ */}
      {/*   MOBILE BOTTOM NAV (< lg)                      */}
      {/* ═══════════════════════════════════════════════ */}
      <div className="lg:hidden fixed bottom-0 left-0 right-0 z-40 bg-white/95 backdrop-blur-xl border-t border-gray-200/80 safe-area-bottom">
        <div className="flex items-center justify-around px-2 py-1.5">
          {mobileNav.map(item => {
            const active = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href));
            const isMore = item.label === "More";
            return isMore ? (
              <button
                key="more"
                onClick={() => setMobileOpen(true)}
                className="flex flex-col items-center gap-0.5 py-1 px-3 rounded-xl transition-all text-gray-400"
              >
                <Menu size={20} strokeWidth={1.6} />
                <span className="text-[9px] font-semibold">More</span>
              </button>
            ) : (
              <Link key={item.href} href={item.href}
                className={`flex flex-col items-center gap-0.5 py-1 px-3 rounded-xl transition-all relative ${
                  active ? "text-primary-600" : "text-gray-400"
                }`}>
                <div className="relative">
                  <item.icon size={20} strokeWidth={active ? 2.2 : 1.6} />
                  {active && <div className="absolute -bottom-1 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-primary-500" />}
                  {item.isNew && (
                    <div className="absolute -top-1 -right-1 w-1.5 h-1.5 bg-gradient-to-r from-emerald-400 to-cyan-400 rounded-full animate-ping" />
                  )}
                </div>
                <span className={`text-[9px] font-semibold ${active ? "text-primary-600" : ""}`}>{item.label}</span>
              </Link>
            );
          })}
        </div>
      </div>

      {/* ═══════════════════════════════════════════════ */}
      {/*   MOBILE DRAWER (full menu)                     */}
      {/* ═══════════════════════════════════════════════ */}
      {mobileOpen && (
        <div className="lg:hidden fixed inset-0 z-50">
          {/* Backdrop */}
          <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={() => setMobileOpen(false)} />
          {/* Drawer */}
          <div className="absolute right-0 top-0 bottom-0 w-[280px] sidebar-bg overflow-y-auto animate-slide-right">
            {/* Header */}
            <div className="flex items-center justify-between px-5 py-5">
              <div className="flex items-center gap-2.5">
                <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-primary-500/20 to-accent-500/20 border border-white/10 flex items-center justify-center">
                  <span className="text-primary-300 text-xs font-bold">{clinic.name.charAt(0).toUpperCase()}</span>
                </div>
                <div>
                  <p className="text-xs font-semibold text-white/80 truncate">{clinic.name}</p>
                  <p className="text-[9px] text-white/25 font-medium">Free Plan</p>
                </div>
              </div>
              <button onClick={() => setMobileOpen(false)} className="text-white/40 hover:text-white p-1">
                <X size={22} />
              </button>
            </div>

            {/* WhatsApp status */}
            <div className="px-4 pb-4">
              <Link href="/connect" onClick={() => setMobileOpen(false)} className={`flex items-center gap-2.5 px-3 py-2.5 rounded-xl transition-all ${
                connected
                  ? "bg-emerald-500/10 border border-emerald-400/20"
                  : "bg-red-500/10 border border-red-400/20"
              }`}>
                <div className={`w-2.5 h-2.5 rounded-full ${connected ? "bg-emerald-400" : "bg-red-400"}`} />
                <span className={`text-xs font-semibold ${connected ? "text-emerald-400" : "text-red-400"}`}>
                  {connected ? "WhatsApp Live" : "Disconnected"}
                </span>
              </Link>
            </div>

            <div className="mx-5 mb-3"><div className="h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent" /></div>

            {/* Nav Links */}
            <nav className="px-3 space-y-0.5">
              {nav.map(item => {
                const active = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href));
                return (
                  <Link key={item.href} href={item.href} onClick={() => setMobileOpen(false)}
                    className={`flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium transition-all relative ${
                      active
                        ? "text-white bg-primary-600/20"
                        : "text-white/40 hover:bg-white/[0.04] hover:text-white/70"
                    }`}>
                    <item.icon size={18} strokeWidth={active ? 2.2 : 1.6}
                      className={active ? "text-primary-400" : "text-white/30"} />
                    <span className="flex items-center gap-2">
                      {item.label}
                      {item.isNew && (
                        <span className="px-1.5 py-0.5 text-[8px] font-bold bg-gradient-to-r from-emerald-500 to-cyan-500 text-white rounded-full uppercase tracking-wide">
                          NEW
                        </span>
                      )}
                    </span>
                    {item.isNew && !active && (
                      <div className="absolute top-2 right-2 w-2 h-2 bg-gradient-to-r from-emerald-400 to-cyan-400 rounded-full animate-ping" />
                    )}
                  </Link>
                );
              })}
            </nav>

            {/* Logout */}
            <div className="px-4 py-6 mt-4 border-t border-white/[0.04]">
              <button onClick={handleLogout}
                className="flex items-center gap-2 px-4 py-2.5 w-full text-xs text-white/30 hover:text-red-400 hover:bg-red-500/10 rounded-xl transition-all">
                <LogOut size={15} /> Sign out
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
