"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import type { SidebarAccordionGroup, SidebarLink } from "@/lib/menu";

function Chevron({ open }: { open: boolean }) {
  return (
    <svg
      viewBox="0 0 24 24"
      className={`h-4 w-4 shrink-0 transition-transform ${open ? "rotate-180" : ""}`}
      fill="currentColor"
      aria-hidden
    >
      <path d="M7.41 8.59 12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z" />
    </svg>
  );
}

function linkIsActive(pathname: string, href: string | undefined, allHrefs: string[]): boolean {
  if (!href) return false;
  if (href === "/dashboard") return pathname === "/dashboard";
  if (pathname === href) return true;
  if (!pathname.startsWith(`${href}/`)) return false;
  return !allHrefs.some((other) => other !== href && other.startsWith(`${href}/`) && (pathname === other || pathname.startsWith(`${other}/`)));
}

function groupHasActive(pathname: string, items: SidebarLink[], allHrefs: string[]): boolean {
  return items.some((item) => linkIsActive(pathname, item.href, allHrefs));
}

function matchesQuery(label: string, query: string): boolean {
  if (!query) return true;
  return label.replace(/\s+/g, "").includes(query);
}

export function SidebarAccordion({
  groups,
  pathname,
  query = "",
}: {
  groups: SidebarAccordionGroup[];
  pathname: string;
  query?: string;
}) {
  const normalizedQuery = query.trim().replace(/\s+/g, "");
  const searching = normalizedQuery.length > 0;

  const allHrefs = useMemo(
    () => groups.flatMap((group) => group.items.map((item) => item.href).filter((href): href is string => Boolean(href))),
    [groups],
  );

  const filteredGroups = useMemo(() => {
    if (!searching) return groups;
    return groups
      .map((group) => ({
        ...group,
        items: matchesQuery(group.title, normalizedQuery)
          ? group.items
          : group.items.filter((item) => matchesQuery(item.label, normalizedQuery)),
      }))
      .filter((group) => group.items.length > 0 || matchesQuery(group.title, normalizedQuery));
  }, [groups, normalizedQuery, searching]);

  const activeGroupIds = useMemo(
    () => groups.filter((group) => groupHasActive(pathname, group.items, allHrefs)).map((group) => group.id),
    [allHrefs, groups, pathname],
  );

  const [extraOpenId, setExtraOpenId] = useState<string | null>(null);

  useEffect(() => {
    setExtraOpenId((current) => (current && activeGroupIds.includes(current) ? null : current));
  }, [activeGroupIds, pathname]);

  const toggle = (id: string) => {
    if (searching) return;
    if (activeGroupIds.includes(id)) return;
    setExtraOpenId((current) => (current === id ? null : id));
  };

  if (searching && filteredGroups.length === 0) {
    return <p className="px-3 py-4 text-center text-xs text-[var(--sidebar-muted)]">موردی یافت نشد</p>;
  }

  return (
    <div className="space-y-1">
      {filteredGroups.map((group) => {
        const hasActive = groupHasActive(pathname, group.items, allHrefs);
        const open = searching || hasActive || extraOpenId === group.id;

        return (
          <div key={group.id} className="rounded-xl">
            <button
              type="button"
              onClick={() => toggle(group.id)}
              className={`flex w-full items-center justify-between rounded-xl px-3 py-2.5 text-sm font-semibold transition ${
                hasActive
                  ? "bg-[var(--sidebar-active)] text-teal-900"
                  : "text-[var(--sidebar-text)] hover:bg-slate-100"
              }`}
            >
              <span>{group.title}</span>
              <Chevron open={open} />
            </button>
            {open ? (
              <div className="mt-0.5 space-y-0.5 pb-1 pe-1 ps-2">
                {group.items.map((item) => {
                  const soon = item.phase === "soon" || !item.href;
                  const active = !soon && linkIsActive(pathname, item.href, allHrefs);
                  if (soon) {
                    return (
                      <div
                        key={item.id}
                        className="flex items-center justify-between rounded-lg px-3 py-2 text-xs text-[var(--sidebar-muted)]"
                      >
                        <span>{item.label}</span>
                        <span className="rounded-full bg-amber-100 px-1.5 py-0.5 text-[9px] font-semibold text-amber-800">
                          به زودی
                        </span>
                      </div>
                    );
                  }
                  return (
                    <Link
                      key={item.id}
                      href={item.href!}
                      className={`block rounded-lg px-3 py-2 text-xs transition ${
                        active
                          ? "bg-[var(--sidebar-active)] font-semibold text-teal-900"
                          : "text-[var(--sidebar-muted)] hover:bg-slate-100 hover:text-[var(--sidebar-text)]"
                      }`}
                    >
                      {item.label}
                    </Link>
                  );
                })}
              </div>
            ) : null}
          </div>
        );
      })}
    </div>
  );
}
