"use client";

import { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  Search,
  LayoutDashboard,
  Users,
  Mail,
  Globe,
  Settings,
  PlusCircle,
  ChevronDown,
  X,
  HelpCircle,
} from "lucide-react";

interface SidebarProps {
  isExpanded?: boolean;
  onToggleExpand?: () => void;
  isMobileOpen?: boolean;
  onCloseMobile?: () => void;
}

interface NavChild {
  label: string;
  href: string;
}

interface NavItem {
  label: string;
  href: string;
  icon: React.ComponentType<{ className?: string }>;
  active: boolean;
  children?: NavChild[];
}

export function Sidebar({
  isExpanded = true,
  isMobileOpen = false,
  onCloseMobile,
}: SidebarProps) {
  const pathname = usePathname();
  const [searchQuery, setSearchQuery] = useState("");

  const allNavItems: NavItem[] = [
    {
      label: "Dashboard",
      href: "/",
      icon: LayoutDashboard,
      active: pathname === "/",
    },
    {
      label: "Contatos",
      href: "/contacts",
      icon: Users,
      active: pathname.startsWith("/contacts"),
      children: [
        { label: "Todos os Contatos", href: "/contacts" },
        { label: "Listas", href: "/contacts/lists" },
        { label: "Tags", href: "/contacts/tags" },
        { label: "Exportar", href: "/contacts/export" },
        { label: "Supressão", href: "/contacts/suppression" },
      ],
    },
    {
      label: "Campanhas",
      href: "/campaigns",
      icon: Mail,
      active: pathname.startsWith("/campaigns"),
    },
    {
      label: "Domínios & Autenticação",
      href: "/settings/domains",
      icon: Globe,
      active: pathname.startsWith("/settings/domains"),
    },
  ];

  // Filter items based on search query
  const filteredNavItems = allNavItems.filter((item) => {
    if (!searchQuery.trim()) return true;
    const query = searchQuery.toLowerCase();
    const matchLabel = item.label.toLowerCase().includes(query);
    const matchChild = item.children?.some((child) =>
      child.label.toLowerCase().includes(query)
    );
    return matchLabel || matchChild;
  });

  const renderNavContent = (expanded: boolean, isMobileView: boolean) => (
    <div className="flex flex-col justify-between h-full select-none py-3">
      {/* Top Header & Search Area */}
      <div className="w-full">
        {expanded ? (
          <div className="px-3 pb-3">
            <div className="relative flex items-center">
              <Search className="w-4 h-4 absolute left-3 text-zinc-400 pointer-events-none" />
              <input
                type="text"
                placeholder="Pesquisar..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-9 pr-7 py-2 text-[12px] bg-[#F5F5F5] border border-zinc-200/50 rounded-lg text-zinc-800 placeholder-zinc-400 focus:outline-none focus:ring-1 focus:ring-[#0F9FDF]/40 focus:border-[#0F9FDF] focus:bg-white transition-all"
              />
              {searchQuery && (
                <button
                  onClick={() => setSearchQuery("")}
                  className="absolute right-2 p-0.5 rounded-full text-zinc-400 hover:text-zinc-600 hover:bg-zinc-200/60"
                  aria-label="Limpar pesquisa"
                >
                  <X className="w-3.5 h-3.5" />
                </button>
              )}
            </div>
          </div>
        ) : (
          <div className="p-2 flex justify-center">
            <button
              title="Pesquisar..."
              className="p-2 text-zinc-500 hover:text-zinc-900 hover:bg-zinc-100 rounded-lg transition-colors"
            >
              <Search className="w-4.5 h-4.5" />
            </button>
          </div>
        )}

        <div className="border-b border-zinc-200/60 w-full mb-3" />

        {/* Navigation List */}
        <div className="px-3 space-y-1">
          {filteredNavItems.map((item, idx) => {
            const Icon = item.icon;
            const isSubmenuOpen =
              expanded &&
              !!item.children &&
              (item.active || searchQuery.trim() !== "");

            return (
              <div key={idx}>
                <Link
                  href={item.href}
                  title={!expanded ? item.label : undefined}
                  aria-label={item.label}
                  aria-current={item.active ? "page" : undefined}
                  aria-expanded={item.children ? isSubmenuOpen : undefined}
                  onClick={() => {
                    if (isMobileView && onCloseMobile) onCloseMobile();
                  }}
                  className={`relative flex items-center gap-3 px-3 py-2.5 rounded-lg text-[13px] transition-all duration-150 group focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0F9FDF] ${
                    item.active
                      ? "bg-[#E7F6FD] text-[#0F9FDF] font-bold"
                      : "text-[#4A4A4A] font-semibold hover:text-zinc-900 hover:bg-zinc-100/70"
                  } ${!expanded ? "justify-center" : "justify-start"}`}
                >
                  <Icon
                    className={`w-4.5 h-4.5 shrink-0 transition-colors ${
                      item.active ? "text-[#0F9FDF]" : "text-zinc-500 group-hover:text-zinc-700"
                    }`}
                  />
                  {expanded && (
                    <span className="truncate flex-1 text-[13px] leading-tight">
                      {item.label}
                    </span>
                  )}
                  {expanded && item.children && (
                    <ChevronDown
                      className={`w-3.5 h-3.5 shrink-0 transition-transform duration-200 ${
                        item.active ? "text-[#0F9FDF]" : "text-zinc-400"
                      } ${isSubmenuOpen ? "rotate-180" : ""}`}
                    />
                  )}
                </Link>

                {item.children && isSubmenuOpen && (
                  <div className="mt-1 ml-3 pl-3 border-l border-zinc-200/80 space-y-1">
                    {item.children.map((child) => {
                      const childActive = pathname === child.href;
                      return (
                        <Link
                          key={child.href}
                          href={child.href}
                          aria-current={childActive ? "page" : undefined}
                          onClick={() => {
                            if (isMobileView && onCloseMobile) onCloseMobile();
                          }}
                          className={`block px-2.5 py-1.5 rounded-md text-[12px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0F9FDF] ${
                            childActive
                              ? "text-[#0F9FDF] font-bold bg-[#E7F6FD]/60"
                              : "text-zinc-600 font-medium hover:text-zinc-900 hover:bg-zinc-100/60"
                          }`}
                        >
                          {child.label}
                        </Link>
                      );
                    })}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* Bottom Footer Actions */}
      <div className="w-full">
        <div className="px-3 pt-2 pb-1 space-y-1">
          <Link
            href="/campaigns/new"
            title={!expanded ? "Nova Campanha" : undefined}
            aria-label="Nova Campanha"
            onClick={() => {
              if (isMobileView && onCloseMobile) onCloseMobile();
            }}
            className={`flex items-center gap-3 px-3 py-2 rounded-lg text-[12.5px] font-semibold text-[#4A4A4A] hover:text-zinc-900 hover:bg-zinc-100/70 transition-all group focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0F9FDF] ${
              !expanded ? "justify-center" : "justify-start"
            }`}
          >
            <PlusCircle className="w-4.5 h-4.5 shrink-0 text-zinc-500 group-hover:text-zinc-700 transition-colors" />
            {expanded && <span className="truncate">Nova Campanha</span>}
          </Link>

          <Link
            href="/settings/domains"
            title={!expanded ? "Configurações" : undefined}
            aria-label="Configurações"
            onClick={() => {
              if (isMobileView && onCloseMobile) onCloseMobile();
            }}
            className={`flex items-center gap-3 px-3 py-2 rounded-lg text-[12.5px] font-semibold text-[#4A4A4A] hover:text-zinc-900 hover:bg-zinc-100/70 transition-all group focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#4BAE36] ${
              !expanded ? "justify-center" : "justify-start"
            }`}
          >
            <Settings className="w-4.5 h-4.5 shrink-0 text-zinc-500 group-hover:text-zinc-700 transition-colors" />
            {expanded && <span className="truncate">Configurações</span>}
          </Link>
        </div>

        <div className="border-t border-zinc-200/60 w-full my-1.5" />

        <div className="px-3 pt-0.5 pb-1">
          <a
            href="https://support.example.com"
            target="_blank"
            rel="noopener noreferrer"
            title={!expanded ? "Precisa de ajuda?" : undefined}
            aria-label="Precisa de ajuda?"
            onClick={() => {
              if (isMobileView && onCloseMobile) onCloseMobile();
            }}
            className={`flex items-center gap-3 px-3 py-2 rounded-lg text-[13px] font-semibold text-[#4A4A4A] hover:text-zinc-900 hover:bg-zinc-100/70 transition-all group focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0F9FDF] ${
              !expanded ? "justify-center" : "justify-start"
            }`}
          >
            <HelpCircle className="w-4.5 h-4.5 shrink-0 text-zinc-500 group-hover:text-zinc-700 transition-colors" />
            {expanded && (
              <span className="truncate text-[13px]">Precisa de ajuda?</span>
            )}
          </a>
        </div>
      </div>
    </div>
  );

  return (
    <>
      {/* ------------------------------------------------------------- */}
      {/* DESKTOP SIDEBAR (FIXED HIGH-PERFORMANCE SIDE NAVIGATION)       */}
      {/* ------------------------------------------------------------- */}
      <aside
        className={`hidden lg:flex fixed top-14 left-0 bottom-0 z-30 bg-white border-r border-zinc-200/80 flex-col transition-all duration-300 ${
          isExpanded ? "w-64" : "w-16"
        }`}
      >
        {renderNavContent(isExpanded, false)}
      </aside>

      {/* ------------------------------------------------------------- */}
      {/* MOBILE DRAWER (OFF-CANVAS WITH BACKDROP OVERLAY)              */}
      {/* ------------------------------------------------------------- */}
      {isMobileOpen && (
        <div className="lg:hidden fixed inset-0 z-50 flex">
          {/* Backdrop */}
          <div
            className="fixed inset-0 bg-black/50 backdrop-blur-xs transition-opacity animate-in fade-in duration-200"
            onClick={onCloseMobile}
            aria-hidden="true"
          />

          {/* Off-canvas Drawer Content */}
          <div className="relative w-64 max-w-[80vw] bg-white h-full shadow-2xl flex flex-col z-50 animate-in slide-in-from-left duration-200 border-r border-zinc-200">
            {/* Drawer Header */}
            <div className="p-4 border-b border-zinc-200/80 flex items-center justify-between">
              <span className="font-extrabold text-sm text-zinc-900">
                Menu Principal
              </span>
              <button
                type="button"
                onClick={onCloseMobile}
                aria-label="Fechar menu de navegação"
                className="p-1.5 rounded-lg text-zinc-500 hover:text-zinc-900 hover:bg-zinc-100 transition-colors cursor-pointer"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Drawer Body */}
            <div className="flex-1 overflow-y-auto">
              {renderNavContent(true, true)}
            </div>
          </div>
        </div>
      )}
    </>
  );
}
