import Link from 'next/link';
import type { ReactNode } from 'react';
import { logoutAction } from '../app/actions';
import { requireAuthToken } from '../lib/auth';
import { getDictionary, getLocale } from '../lib/i18n';
import { LanguageSwitcher } from './language-switcher';

type Props = {
  children: ReactNode;
  currentPath: string;
  title?: string;
  searchPlaceholder?: string;
  searchValue?: string;
  searchActionPath?: string;
  searchQueryName?: string;
};

function isActive(href: string, currentPath: string) {
  if (href === '/dashboard') {
    return currentPath === href;
  }

  return currentPath === href || currentPath.startsWith(`${href}/`);
}

function SearchIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <path
        d="M11 5a6 6 0 1 0 0 12 6 6 0 0 0 0-12Zm0 0c3.3 0 6 2.7 6 6m-1.5 5.5L20 21"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function BellIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <path
        d="M9.5 18a2.5 2.5 0 0 0 5 0M6 17h12l-1.4-1.6a2 2 0 0 1-.5-1.3V10a4.1 4.1 0 0 0-8.2 0v4.1a2 2 0 0 1-.5 1.3L6 17Z"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function HelpIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <path
        d="M9.6 9.1a2.9 2.9 0 1 1 4.8 2.2c-.9.7-1.7 1.3-1.7 2.4v.4M12 17.6h.01"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

export async function DashboardShell({
  children,
  currentPath,
  title,
  searchPlaceholder,
  searchValue,
  searchActionPath,
  searchQueryName,
}: Props) {
  await requireAuthToken();
  const locale = await getLocale();
  const dict = await getDictionary();
  const isConversationsRoute = currentPath.startsWith('/dashboard/conversations');

  const navItems = [
    { href: '/dashboard', label: dict.dashboard.navOverview, icon: 'dashboard' },
    { href: '/dashboard/conversations', label: dict.dashboard.navConversations, icon: 'chat' },
    { href: '/dashboard/templates', label: dict.dashboard.navTemplates, icon: 'description' },
    { href: '/dashboard/logs', label: 'Analytics', icon: 'monitoring' },
  ];

  const utilityItems = [
    { href: '/dashboard/contacts', label: dict.dashboard.navContacts, icon: 'contacts' },
    { href: '/dashboard/campaigns', label: dict.dashboard.navCampaigns, icon: 'campaign' },
    { href: '/dashboard/users', label: dict.dashboard.navUsers, icon: 'group' },
    { href: '/dashboard/roles', label: dict.dashboard.navRoles, icon: 'admin_panel_settings' },
  ];

  const settingsItems = [
    { href: '/dashboard/settings/whatsapp-api', label: 'WhatsApp API Setting', icon: 'link' },
    { href: '/dashboard/settings/security', label: 'Security', icon: 'security' },
    { href: '/dashboard/settings/webhook-logs', label: 'Webhook Logs', icon: 'webhook' },
    { href: '/dashboard/settings/audit-trail', label: 'Audit Trail', icon: 'history' },
  ];
  const isSettingsSection = currentPath.startsWith('/dashboard/settings');

  return (
    <div className="dashboard-app">
      <aside className="dashboard-sidebar">
        <div className="dashboard-brand">
          <h1>BizOne</h1>
          <p>Enterprise API</p>
        </div>

        <Link href="/dashboard/campaigns" className="dashboard-primary-action">
          <span className="material-symbols-outlined">add</span>
          {dict.dashboard.newMessage}
        </Link>

        <div className="dashboard-sidebar-scroll">
          <nav className="dashboard-nav">
            {navItems.map((item) => (
              <Link
                key={item.href}
                href={item.href}
                className={isActive(item.href, currentPath) ? 'dashboard-nav-link is-active' : 'dashboard-nav-link'}
              >
                <span className="material-symbols-outlined">{item.icon}</span>
                {item.label}
              </Link>
            ))}
          </nav>

          <div className="dashboard-nav-secondary">
            {utilityItems.map((item) => (
              <Link
                key={item.href}
                href={item.href}
                className={isActive(item.href, currentPath) ? 'dashboard-subnav-link is-active' : 'dashboard-subnav-link'}
              >
                <span className="material-symbols-outlined">{item.icon}</span>
                {item.label}
              </Link>
            ))}
          </div>

          <div className="dashboard-sidebar-footer">
            <details className="dashboard-settings-accordion" open={isSettingsSection}>
              <summary className={isSettingsSection ? 'dashboard-nav-link is-active' : 'dashboard-nav-link'}>
                <span className="dashboard-nav-link-main">
                  <span className="material-symbols-outlined">settings</span>
                  {dict.dashboard.navSettings}
                </span>
                <span className="material-symbols-outlined dashboard-settings-caret">expand_more</span>
              </summary>
              <div className="dashboard-settings-subnav">
                {settingsItems.map((item) => (
                  <Link
                    key={item.href}
                    href={item.href}
                    className={isActive(item.href, currentPath) ? 'dashboard-settings-link is-active' : 'dashboard-settings-link'}
                  >
                    <span className="material-symbols-outlined">{item.icon}</span>
                    {item.label}
                  </Link>
                ))}
              </div>
            </details>
            <form action={logoutAction}>
              <button type="submit" className="dashboard-logout-button">
                <span className="material-symbols-outlined">logout</span>
                {dict.common.logout}
              </button>
            </form>
          </div>
        </div>
      </aside>

      <div className={isConversationsRoute ? 'dashboard-main dashboard-main-conversations' : 'dashboard-main'}>
        <header className="dashboard-topbar">
          <div className="dashboard-topbar-left">
            <h2>{title || dict.common.overview}</h2>
            {searchPlaceholder ? (
              <>
                <div className="dashboard-topbar-divider" />
                <form className="dashboard-searchbar" action={searchActionPath || currentPath}>
                  <span className="material-symbols-outlined">search</span>
                  <input
                    type="search"
                    name={searchQueryName || 'q'}
                    placeholder={searchPlaceholder}
                    defaultValue={searchValue || ''}
                  />
                </form>
              </>
            ) : null}
            <LanguageSwitcher
              currentLocale={locale}
              label={dict.common.language}
              englishLabel={dict.common.english}
              indonesianLabel={dict.common.indonesian}
              submitLabel={dict.common.save}
              variant="compact"
            />
          </div>
          <div className="dashboard-topbar-actions">
            <button type="button" className="dashboard-icon-button" aria-label={dict.common.search}>
              <SearchIcon />
            </button>
            <button type="button" className="dashboard-icon-button" aria-label="notifications">
              <BellIcon />
            </button>
            <button type="button" className="dashboard-icon-button" aria-label={dict.common.helpCenter}>
              <HelpIcon />
            </button>
            <div className="dashboard-profile">
              <div>
                <strong>{dict.common.adminUser}</strong>
                <span>{dict.common.superAdmin}</span>
              </div>
              <div className="dashboard-avatar">A</div>
            </div>
          </div>
        </header>
        <main className={isConversationsRoute ? 'dashboard-content dashboard-content-conversations' : 'dashboard-content'}>
          {children}
        </main>
      </div>
    </div>
  );
}
