'use client';

import React, { useEffect, useRef, useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { fetchMe, isAuthenticated } from '@/lib/auth';
import SettingsModal from '@/components/SettingsModal';
import { useIsMobile } from '@/lib/useIsMobile';
import { useTranslation } from '@/lib/i18n';
import type { TranslationKey } from '@/lib/i18n/messages/en';
import { adminNavItemIsActive } from '@/lib/admin-nav';

// Admin access is controlled by the ADMIN_EMAILS env var on the backend.
// The layout fetches /api/auth/me to get the server-authoritative `is_admin` flag,
// preventing any client-side bypass.

// ─── Logo (same as AppHeader) ─────────────────────────────────────

function InvestibookLogo({ size = 26 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="ib-admin-bg" x1="0" y1="0" x2="32" y2="32" gradientUnits="userSpaceOnUse">
          <stop offset="0%" stopColor="#5c5fbc" />
          <stop offset="100%" stopColor="#7c7fdc" />
        </linearGradient>
      </defs>
      <rect width="32" height="32" rx="7" fill="url(#ib-admin-bg)" />
      <rect x="5" y="3" width="22" height="26" rx="3" fill="white" fillOpacity="0.18" />
      <rect x="5" y="3" width="22" height="26" rx="3" stroke="white" strokeWidth="1.5" />
      <rect x="8" y="7" width="7" height="5" rx="1" fill="white" fillOpacity="0.7" />
      <rect x="17" y="8" width="7" height="1.5" rx="0.75" fill="white" fillOpacity="0.5" />
      <rect x="17" y="11" width="5" height="1.5" rx="0.75" fill="white" fillOpacity="0.5" />
      <rect x="8" y="16" width="16" height="1.5" rx="0.75" fill="white" fillOpacity="0.4" />
      <rect x="8" y="19.5" width="13" height="1.5" rx="0.75" fill="white" fillOpacity="0.4" />
      <rect x="8" y="23" width="14" height="1.5" rx="0.75" fill="white" fillOpacity="0.4" />
    </svg>
  );
}

// ─── User Dropdown ────────────────────────────────────────────────

function UserDropdown({
  email,
  onSettings,
  onLogout,
}: {
  email: string;
  onSettings: () => void;
  onLogout: () => void;
}) {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const close = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, [open]);

  return (
    <div ref={ref} style={{ position: 'relative', display: 'inline-flex', flexShrink: 0 }}>
      <button
        onClick={() => setOpen((v) => !v)}
        title={email}
        style={{
          width: '32px',
          height: '32px',
          minWidth: '32px',
          borderRadius: '50%',
          background: 'linear-gradient(135deg, #5c5fbc, #7c7fdc)',
          border: 'none',
          cursor: 'pointer',
          padding: 0,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: '13px',
          fontWeight: 700,
          color: '#fff',
          flexShrink: 0,
          boxSizing: 'border-box',
          transition: 'opacity 0.15s',
        }}
        onMouseEnter={(e) => (e.currentTarget.style.opacity = '0.85')}
        onMouseLeave={(e) => (e.currentTarget.style.opacity = '1')}
      >
        {email[0].toUpperCase()}
      </button>
      {open && (
        <div
          style={{
            position: 'absolute',
            top: 'calc(100% + 8px)',
            right: 0,
            background: '#fff',
            borderRadius: '10px',
            boxShadow: '0 4px 20px rgba(0,0,0,0.12)',
            border: '1px solid #eee',
            overflow: 'hidden',
            zIndex: 300,
            minWidth: '200px',
          }}
        >
          <div style={{ padding: '12px 16px', borderBottom: '1px solid #f0f0f0' }}>
            <div style={{ fontSize: '13px', color: '#999', marginBottom: '2px' }}>{t('adminLayout.signedInAsLabel')}</div>
            <div
              style={{
                fontSize: '13px',
                fontWeight: 600,
                color: '#333',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
              }}
            >
              {email}
            </div>
          </div>
          {[
            { key: 'settings', label: t('adminLayout.settingsNav'), onClick: () => { setOpen(false); onSettings(); } },
            { key: 'signout', label: t('adminLayout.signOutNav'), onClick: () => { setOpen(false); onLogout(); } },
          ].map((item) => (
            <button
              key={item.key}
              onClick={item.onClick}
              style={{
                display: 'block',
                width: '100%',
                padding: '11px 16px',
                background: 'none',
                border: 'none',
                cursor: 'pointer',
                textAlign: 'left',
                fontSize: '14px',
                color: item.key === 'signout' ? '#888' : '#333',
              }}
              onMouseEnter={(e) => (e.currentTarget.style.background = '#f7f7f7')}
              onMouseLeave={(e) => (e.currentTarget.style.background = 'none')}
            >
              {item.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Sidebar nav items ────────────────────────────────────────────

interface NavItem {
  label: string;
  href: string;
  icon: string;
  description: string;
}

function getNavItems(
  t: (key: TranslationKey, vars?: Record<string, string | number>) => string,
): NavItem[] {
  return [
    {
      label: t('adminLayout.navIncidents'),
      href: '/admin/incidents',
      icon: '🗂️',
      description: t('adminLayout.navIncidentsDesc'),
    },
    {
      label: t('adminLayout.navWeeklyReport'),
      href: '/admin/weekly-report',
      icon: '📝',
      description: t('adminLayout.navWeeklyReportDesc'),
    },
    {
      label: t('adminLayout.navEvaluations'),
      href: '/admin/evaluations',
      icon: '🎯',
      description: t('adminLayout.navEvaluationsDesc'),
    },
    {
      label: t('adminLayout.navStats'),
      href: '/admin/stats',
      icon: '📊',
      description: t('adminLayout.navStatsDesc'),
    },
    {
      label: t('adminLayout.navClinic'),
      href: '/admin/clinic-state',
      icon: '🏥',
      description: t('adminLayout.navClinicDesc'),
    },
    {
      label: t('adminLayout.navTriagePilot'),
      href: '/admin/triagepilot',
      icon: '🧭',
      description: t('adminLayout.navTriagePilotDesc'),
    },
    {
      label: t('adminLayout.navUsers'),
      href: '/admin/user',
      icon: '👤',
      description: t('adminLayout.navUsersDesc'),
    },
  ];
}

// ─── Admin Layout ─────────────────────────────────────────────────

export default function AdminLayout({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const { t } = useTranslation();
  const pathname = usePathname();
  const isMobile = useIsMobile();
  const [email, setEmail] = useState<string | null>(null);
  const [showSettings, setShowSettings] = useState(false);
  const NAV_ITEMS = getNavItems(t);
  const isWeeklyReportDevPreview =
    process.env.NODE_ENV === 'development' && pathname?.startsWith('/admin/weekly-report');

  useEffect(() => {
    if (isWeeklyReportDevPreview) {
      setEmail('local-preview@investibook.dev');
      return;
    }

    setEmail(null);
    if (!isAuthenticated()) {
      router.replace(`/login?redirect=${encodeURIComponent(window.location.pathname)}`);
      return;
    }
    fetchMe()
      .then((me) => {
        if (!me.is_admin) {
          router.replace('/');
          return;
        }
        setEmail(me.email);
      })
      .catch(() => router.replace('/'));
  }, [router, isWeeklyReportDevPreview]);

  function handleLogout() {
    localStorage.removeItem('investibook_token');
    localStorage.removeItem('investibook_email');
    router.push('/login');
  }

  if (!email) return null;

  return (
    <div
      style={{
        minHeight: '100vh',
        background: 'linear-gradient(135deg, #f0f2ff 0%, #eef0fb 100%)',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {/* ── Top header ── */}
      <header
        style={{
          position: 'sticky',
          top: 0,
          zIndex: 100,
          height: '52px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: isMobile ? '0 16px' : '0 40px',
          background: 'transparent',
          flexShrink: 0,
        }}
      >
        {/* Left: logo + brand + admin badge */}
        <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
          <button
            onClick={() => router.push('/')}
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '9px',
              background: 'none',
              border: 'none',
              cursor: 'pointer',
              padding: 0,
            }}
          >
            <InvestibookLogo size={26} />
            {!isMobile && (
              <span
                style={{
                  fontSize: '16px',
                  fontWeight: 700,
                  color: '#1a1a2e',
                  letterSpacing: '-0.3px',
                }}
              >
                {t('adminLayout.brandLabel')}
              </span>
            )}
          </button>
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '6px',
              color: '#6b7280',
            }}
          >
            <span style={{ fontSize: '14px', color: '#9ca3af' }}>/</span>
            <span
              style={{
                fontSize: '13px',
                fontWeight: 600,
                color: '#5c5fbc',
                background: 'rgba(92,95,188,0.08)',
                padding: '2px 8px',
                borderRadius: '5px',
                letterSpacing: '0.3px',
              }}
            >
              {t('adminLayout.adminBadgeLabel')}
            </span>
          </div>
        </div>

        {/* Right: nav back link + user avatar */}
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          {!isMobile && (
            <button
              onClick={() => router.push('/')}
              style={{
                background: 'none',
                border: 'none',
                cursor: 'pointer',
                padding: '6px 12px',
                fontSize: '14px',
                fontWeight: 500,
                color: '#6b7280',
                borderRadius: '6px',
                transition: 'color 0.15s, background 0.15s',
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.color = '#1a1a2e';
                e.currentTarget.style.background = '#f5f5f5';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.color = '#6b7280';
                e.currentTarget.style.background = 'none';
              }}
            >
              {t('adminLayout.workspacesNav')}
            </button>
          )}
          {!isMobile && <div style={{ width: '1px', height: '18px', background: '#e5e7eb', margin: '0 2px' }} />}
          <UserDropdown
            email={email}
            onSettings={() => setShowSettings(true)}
            onLogout={handleLogout}
          />
        </div>
      </header>

      {/* ── Mobile: horizontal tab nav ── */}
      {isMobile && (
        <nav
          style={{
            display: 'flex',
            overflowX: 'auto',
            padding: '8px 16px',
            gap: '6px',
            background: 'rgba(255,255,255,0.8)',
            backdropFilter: 'blur(8px)',
            borderBottom: '1px solid rgba(92,95,188,0.1)',
            flexShrink: 0,
            WebkitOverflowScrolling: 'touch',
            scrollbarWidth: 'none',
          }}
        >
          {NAV_ITEMS.map((item) => {
            const isActive = adminNavItemIsActive(pathname, item);
            return (
              <button
                key={item.href}
                onClick={() => router.push(item.href)}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '6px',
                  padding: '7px 14px',
                  borderRadius: '20px',
                  border: isActive ? '1.5px solid rgba(92,95,188,0.3)' : '1.5px solid transparent',
                  cursor: 'pointer',
                  whiteSpace: 'nowrap',
                  flexShrink: 0,
                  background: isActive
                    ? 'linear-gradient(135deg, rgba(92,95,188,0.12), rgba(124,127,220,0.08))'
                    : 'rgba(0,0,0,0.04)',
                  fontSize: '13px',
                  fontWeight: isActive ? 600 : 500,
                  color: isActive ? '#5c5fbc' : '#374151',
                  transition: 'all 0.15s',
                }}
              >
                <span style={{ fontSize: '14px' }}>{item.icon}</span>
                {item.label}
              </button>
            );
          })}
        </nav>
      )}

      {/* ── Body (sidebar + content) ── */}
      <div
        style={{
          display: 'flex',
          flex: 1,
          minHeight: 0,
          padding: isMobile ? '16px 16px 32px 16px' : '0 40px 40px 40px',
          gap: '24px',
        }}
      >
        {/* ── Left sidebar (desktop only) ── */}
        {!isMobile && (
          <aside
            style={{
              width: '220px',
              flexShrink: 0,
              background: 'rgba(255,255,255,0.7)',
              backdropFilter: 'blur(8px)',
              borderRadius: '14px',
              border: '1px solid rgba(92,95,188,0.1)',
              boxShadow: '0 2px 12px rgba(92,95,188,0.07)',
              padding: '16px 12px',
              alignSelf: 'flex-start',
              position: 'sticky',
              top: '68px',
            }}
          >
            <div
              style={{
                fontSize: '11px',
                fontWeight: 700,
                color: '#9ca3af',
                letterSpacing: '0.08em',
                textTransform: 'uppercase',
                padding: '0 8px',
                marginBottom: '10px',
              }}
            >
              {t('adminLayout.managementSection')}
            </div>

            <nav style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
              {NAV_ITEMS.map((item) => {
                const isActive = adminNavItemIsActive(pathname, item);
                return (
                  <button
                    key={item.href}
                    onClick={() => router.push(item.href)}
                    style={{
                      display: 'flex',
                      alignItems: 'flex-start',
                      gap: '10px',
                      padding: '10px 10px',
                      borderRadius: '9px',
                      border: 'none',
                      cursor: 'pointer',
                      textAlign: 'left',
                      background: isActive
                        ? 'linear-gradient(135deg, rgba(92,95,188,0.12), rgba(124,127,220,0.08))'
                        : 'none',
                      transition: 'background 0.15s',
                      width: '100%',
                    }}
                    onMouseEnter={(e) => {
                      if (!isActive) e.currentTarget.style.background = 'rgba(92,95,188,0.06)';
                    }}
                    onMouseLeave={(e) => {
                      if (!isActive) e.currentTarget.style.background = 'none';
                    }}
                  >
                    <span style={{ fontSize: '16px', flexShrink: 0, marginTop: '1px' }}>{item.icon}</span>
                    <div>
                      <div
                        style={{
                          fontSize: '13px',
                          fontWeight: isActive ? 600 : 500,
                          color: isActive ? '#5c5fbc' : '#374151',
                          lineHeight: 1.3,
                        }}
                      >
                        {item.label}
                      </div>
                      <div
                        style={{
                          fontSize: '11px',
                          color: isActive ? '#7c7fdc' : '#9ca3af',
                          marginTop: '2px',
                          lineHeight: 1.4,
                        }}
                      >
                        {item.description}
                      </div>
                    </div>
                    {isActive && (
                      <div
                        style={{
                          width: '3px',
                          height: '100%',
                          background: 'linear-gradient(135deg, #5c5fbc, #7c7fdc)',
                          borderRadius: '2px',
                          position: 'absolute',
                          left: 0,
                          top: 0,
                        }}
                      />
                    )}
                  </button>
                );
              })}
            </nav>

            {/* Sidebar footer info */}
            <div
              style={{
                marginTop: '20px',
                padding: '10px',
                borderTop: '1px solid rgba(92,95,188,0.1)',
              }}
            >
              <div style={{ fontSize: '11px', color: '#9ca3af', lineHeight: 1.5 }}>
                {t('adminLayout.adminAccessOnly')}
                <br />
                {t('adminLayout.changesImmediately')}
              </div>
            </div>
          </aside>
        )}

        {/* ── Main content area ── */}
        <main
          style={{
            flex: 1,
            minWidth: 0,
            overflowY: 'auto',
          }}
        >
          {children}
        </main>
      </div>

      {showSettings && <SettingsModal open={showSettings} onClose={() => setShowSettings(false)} />}
    </div>
  );
}
