import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import type { Locale } from '../../data/site';
import type { NavItem } from '../../data/navigation';
import { localizedPath } from '../../i18n/utils';

type Props = {
  locale: Locale;
  nav: NavItem[];
  callHref: string;
  callLabel: string;
  currentPath: string;
  email: string;
  localeUrls: Record<Locale, string>;
};

function isActive(href: string, currentPath: string): boolean {
  const normalizedCurrent = currentPath === '' ? '/' : currentPath;
  if (href === '/' || href === '/en/') {
    return normalizedCurrent === href || normalizedCurrent === href.replace(/\/$/, '') || (href === '/' && normalizedCurrent === '/');
  }
  return normalizedCurrent.startsWith(href);
}

function CloseIcon() {
  return (
    <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
    </svg>
  );
}

function ChevronIcon() {
  return (
    <svg className="h-4 w-4 opacity-40 rtl:rotate-180" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
    </svg>
  );
}

function ExpandIcon({ open }: { open: boolean }) {
  return (
    <svg
      className={`h-4 w-4 opacity-40 transition-transform duration-200 ${open ? 'rotate-180' : ''}`}
      fill="none"
      stroke="currentColor"
      viewBox="0 0 24 24"
      aria-hidden="true"
    >
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
    </svg>
  );
}

export default function MobileNav({
  locale,
  nav,
  callHref,
  callLabel,
  currentPath,
  email,
  localeUrls,
}: Props) {
  const [open, setOpen] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [expandedHref, setExpandedHref] = useState<string | null>(() => {
    const activeParent = nav.find(
      (item) => item.children && item.children.some((child) => isActive(child.href, currentPath)),
    );
    return activeParent?.href ?? null;
  });
  const isRtl = locale === 'ar';

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!open) return;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = previousOverflow;
    };
  }, [open]);

  const drawer =
    open && mounted
      ? createPortal(
          <div className="fixed inset-0 z-[100] lg:hidden" role="presentation">
            <div
              className="absolute inset-0 bg-primary/40 backdrop-blur-sm animate-fade-in"
              onClick={() => setOpen(false)}
              aria-hidden="true"
            />

            <nav
              className="mobile-drawer absolute inset-y-0 start-0 flex w-[min(20rem,88vw)] flex-col overflow-hidden bg-neutral text-neutral-content shadow-2xl"
              aria-label={isRtl ? 'القائمة' : 'Menu'}
            >
              {/* Header */}
              <div className="flex items-center justify-between bg-neutral px-5 py-4">
                <a href={localizedPath(locale, '')} onClick={() => setOpen(false)} className="shrink-0">
                  <img
                    src="/brand/logo-header.png"
                    alt=""
                    className="h-10 w-auto brightness-110"
                    width={602}
                    height={256}
                  />
                </a>
                <button
                  type="button"
                  className="inline-flex h-10 w-10 items-center justify-center rounded-lg border border-white/20 text-primary-content transition-colors hover:bg-white/10 hover:text-secondary"
                  onClick={() => setOpen(false)}
                  aria-label={isRtl ? 'إغلاق' : 'Close'}
                >
                  <CloseIcon />
                </button>
              </div>

              {/* Nav links */}
              <div className="flex-1 overflow-y-auto px-4 py-5">
                <p className="mb-3 px-2 text-xs font-semibold uppercase tracking-wider text-neutral-content/40">
                  {isRtl ? 'التنقل' : 'Navigation'}
                </p>
                <ul className="space-y-1">
                  {nav.map((item) => {
                    const active = isActive(item.href, currentPath);
                    const isExpanded = expandedHref === item.href;

                    if (item.children) {
                      return (
                        <li key={item.href}>
                          <button
                            type="button"
                            className={[
                              'flex w-full items-center justify-between rounded-xl px-4 py-3.5 text-[0.95rem] font-medium transition-colors',
                              active
                                ? 'bg-white/10 text-secondary'
                                : 'text-neutral-content/75 hover:bg-white/5 hover:text-neutral-content',
                            ].join(' ')}
                            onClick={() => setExpandedHref(isExpanded ? null : item.href)}
                            aria-expanded={isExpanded}
                          >
                            <span className="flex items-center gap-3">
                              {active && (
                                <span className="h-1.5 w-1.5 shrink-0 rounded-full bg-secondary" aria-hidden="true" />
                              )}
                              {item.label[locale]}
                            </span>
                            <ExpandIcon open={isExpanded} />
                          </button>
                          {isExpanded && (
                            <ul className="mt-1 space-y-1 ps-4">
                              {item.children.map((child) => {
                                const childActive = isActive(child.href, currentPath);
                                return (
                                  <li key={child.href}>
                                    <a
                                      href={child.href}
                                      onClick={() => setOpen(false)}
                                      className={[
                                        'flex items-center gap-3 rounded-xl px-4 py-3 text-sm transition-colors',
                                        childActive
                                          ? 'bg-white/10 text-secondary'
                                          : 'text-neutral-content/60 hover:bg-white/5 hover:text-neutral-content',
                                      ].join(' ')}
                                      aria-current={childActive ? 'page' : undefined}
                                    >
                                      {child.label[locale]}
                                    </a>
                                  </li>
                                );
                              })}
                            </ul>
                          )}
                        </li>
                      );
                    }

                    return (
                      <li key={item.href}>
                        <a
                          href={item.href}
                          onClick={() => setOpen(false)}
                          className={[
                            'flex items-center justify-between rounded-xl px-4 py-3.5 text-[0.95rem] font-medium transition-colors',
                            active
                              ? 'bg-white/10 text-secondary'
                              : 'text-neutral-content/75 hover:bg-white/5 hover:text-neutral-content',
                          ].join(' ')}
                          aria-current={active ? 'page' : undefined}
                        >
                          <span className="flex items-center gap-3">
                            {active && (
                              <span className="h-1.5 w-1.5 shrink-0 rounded-full bg-secondary" aria-hidden="true" />
                            )}
                            {item.label[locale]}
                          </span>
                          <ChevronIcon />
                        </a>
                      </li>
                    );
                  })}
                </ul>
              </div>

              {/* Footer */}
              <div className="mt-auto">
                <div className="space-y-4 px-4 py-5">
                  <div className="flex justify-end items-center gap-1 text-sm">
                    {(['ar', 'en'] as const).map((loc, i) => (
                      <span key={loc} className="flex gap-1">
                        {i > 0 && <span className="text-neutral-content/25" aria-hidden="true">·</span>}
                        <a
                          href={localeUrls[loc]}
                          className={[
                            'transition-colors',
                            loc === locale
                              ? 'text-neutral-content/90'
                              : 'text-neutral-content/40 hover:text-neutral-content/70',
                          ].join(' ')}
                          hrefLang={loc}
                          aria-current={loc === locale ? 'true' : undefined}
                        >
                          {loc === 'ar' ? 'عربي' : 'English'}
                        </a>
                      </span>
                    ))}
                  </div>
                </div>

                <a
                  href={callHref}
                  data-gads-conversion="call"
                  className="flex w-full items-center justify-center gap-2 bg-secondary py-4 text-sm font-semibold text-secondary-content transition-[filter] hover:brightness-95"
                >
                  <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                  </svg>
                  {callLabel}
                </a>
              </div>
            </nav>
          </div>,
          document.body,
        )
      : null;

  return (
    <div className="lg:hidden h-full">
      <button
        type="button"
        className="inline-flex h-full min-h-[4.5rem] w-14 items-center justify-center px-0 text-primary-content/80 transition-colors hover:bg-white/10 hover:text-secondary sm:w-16"
        aria-label={isRtl ? 'فتح القائمة' : 'Open menu'}
        aria-expanded={open}
        onClick={() => setOpen(true)}
      >
        <svg className="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
        </svg>
      </button>
      {drawer}
    </div>
  );
}
