'use client';

import './platform.css';
import React, { useEffect, useState } from 'react';
import { Dropdown, Grid, Layout, Tooltip, type MenuProps } from 'antd';
import { shapeTokens } from '../../theme/tokens';
import { Icon } from '../ui/Icon';
import { UserAvatar } from '../ui/UserAvatar';
import { useAppTheme } from '../../context/ThemeContext';
import type { AuthUser } from '../../context/AuthContext';
import { PLATFORM_NAV_GROUPS } from './platformData';
import { auditActionLabel, describeAuditDetails, relTime } from './platformFormat';
import type { PlatformAuditLogItem, PlatformRouteId } from './platformTypes';

const AUDIT_SEEN_KEY = 'tcx_platform_audit_seen_at';
const AUDIT_CLEARED_KEY = 'tcx_platform_audit_cleared_at';

function readAuditSeenAt(): number {
  try {
    return Number(window.localStorage.getItem(AUDIT_SEEN_KEY)) || 0;
  } catch {
    return 0;
  }
}

function readAuditClearedAt(): number {
  try {
    return Number(window.localStorage.getItem(AUDIT_CLEARED_KEY)) || 0;
  } catch {
    return 0;
  }
}

const { Header, Sider, Content } = Layout;

const TOOLTIP_STYLES = {
  container: {
    minHeight: 'unset',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    padding: '5px 9px',
    fontSize: 13,
    lineHeight: 1.25,
  } as React.CSSProperties,
};

export function PlatformShell({ user, activeRoute, organizationsCount, auditLogs, onNavigate, onOpenPalette, onLogout, children }: { user: AuthUser; activeRoute: PlatformRouteId; organizationsCount: number; auditLogs: PlatformAuditLogItem[]; onNavigate: (route: PlatformRouteId) => void; onOpenPalette: () => void; onLogout: () => Promise<void>; children: React.ReactNode }) {
  const { mode, prefs, updatePrefs, toggleTheme } = useAppTheme();
  const screens = Grid.useBreakpoint();
  const isMobile = screens.lg === false;

  const collapsed = prefs.collapsed;
  const [mobileOpen, setMobileOpen] = useState(false);
  const [auditSeenAt, setAuditSeenAt] = useState(readAuditSeenAt);
  const [auditClearedAt, setAuditClearedAt] = useState(readAuditClearedAt);
  const latestAuditAt = auditLogs[0] ? new Date(auditLogs[0].createdAt).getTime() : 0;
  const effectiveSeenAt = activeRoute === 'p-audit' ? Math.max(auditSeenAt, latestAuditAt) : auditSeenAt;
  const unseenAuditCount = auditLogs.filter((log) => {
    const time = new Date(log.createdAt).getTime();
    return time > effectiveSeenAt && time > auditClearedAt;
  }).length;

  const markAuditSeen = React.useCallback(() => {
    if (!latestAuditAt) return;
    setAuditSeenAt(latestAuditAt);
    try {
      window.localStorage.setItem(AUDIT_SEEN_KEY, String(latestAuditAt));
    } catch {
      // Storage can be blocked; the dot then simply resets next visit.
    }
  }, [latestAuditAt]);

  const clearAuditLogs = React.useCallback(() => {
    const now = Date.now();
    setAuditClearedAt(now);
    setAuditSeenAt(now);
    try {
      window.localStorage.setItem(AUDIT_CLEARED_KEY, String(now));
      window.localStorage.setItem(AUDIT_SEEN_KEY, String(now));
    } catch {
      // Storage can be blocked
    }
  }, []);

  const isCollapsed = !isMobile && collapsed;

  useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        onOpenPalette();
      }
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [onOpenPalette]);

  const handleNavClick = (route: PlatformRouteId) => {
    if (route === 'p-audit' || activeRoute === 'p-audit') markAuditSeen();
    onNavigate(route);
    setMobileOpen(false);
  };

  const brandMenuItems: MenuProps['items'] = [
    {
      key: 'header',
      type: 'group',
      label: 'Platform navigation',
    },
    {
      key: 'p-overview',
      icon: <Icon name="dashboard" size={15} />,
      label: 'Platform overview',
      onClick: () => handleNavClick('p-overview'),
    },
    {
      key: 'p-tenants',
      icon: <Icon name="accounts" size={15} />,
      label: 'Organizations directory',
      onClick: () => handleNavClick('p-tenants'),
    },
    {
      key: 'p-audit',
      icon: <Icon name="fileText" size={15} />,
      label: 'Platform audit logs',
      onClick: () => handleNavClick('p-audit'),
    },
  ];

  const visibleAuditLogs = auditLogs
    .filter((log) => new Date(log.createdAt).getTime() > auditClearedAt)
    .slice(0, 5);

  const notifMenuItems: MenuProps['items'] = [
    {
      key: 'notif-title',
      type: 'group',
      label: (
        <div className="flex items-center justify-between pr-1">
          <span>Recent audit events</span>
          {visibleAuditLogs.length > 0 && (
            <button
              type="button"
              className="cursor-pointer border-0 bg-transparent p-0 text-[11px] font-medium text-[var(--tcx-primary)] hover:underline"
              onClick={(e) => {
                e.stopPropagation();
                clearAuditLogs();
              }}
            >
              Clear
            </button>
          )}
        </div>
      ),
    },
    ...visibleAuditLogs.map((log) => ({
      key: log.id,
      icon: <Icon name="shield" size={14} />,
      label: (
        <div className="flex max-w-[260px] flex-col">
          <span className="truncate font-medium text-[var(--tcx-text)]">{auditActionLabel(log.action)}</span>
          <span className="truncate text-[11.5px] text-[var(--tcx-text-2)]">{describeAuditDetails(log.action, log.metadata)}</span>
          <span className="truncate text-[11.5px] text-[var(--tcx-muted)]">
            {log.actor?.name ?? 'System'} · {relTime(log.createdAt)}
          </span>
        </div>
      ),
      onClick: () => handleNavClick('p-audit'),
    })),
    ...(visibleAuditLogs.length === 0
      ? [
          {
            key: 'empty',
            label: <span className="text-[12.5px] text-[var(--tcx-muted)]">No new audit events</span>,
            disabled: true,
          },
        ]
      : []),
    { type: 'divider' as const },
    {
      key: 'all-audit',
      label: <span className="font-medium text-[var(--tcx-primary)]">View all platform audit logs</span>,
      onClick: () => handleNavClick('p-audit'),
    },
  ];

  const userMenuItems: MenuProps['items'] = [
    {
      key: 'identity',
      label: (
        <div className="flex items-center gap-3 py-1">
          <UserAvatar name={user.name} size={36} />
          <div className="min-w-0">
            <div className="truncate text-[13.5px] font-semibold text-[var(--tcx-text)]">{user.name}</div>
            <div className="truncate text-[12px] text-[var(--tcx-muted)]">{user.email}</div>
            <div className="text-[11px] font-medium text-[var(--tcx-primary)]">Super administrator</div>
          </div>
        </div>
      ),
      disabled: true,
    },
    { type: 'divider' },
    {
      key: 'logout',
      icon: <Icon name="logout" size={15} />,
      label: 'Sign out',
      danger: true,
      onClick: () => {
        void onLogout();
      },
    },
  ];

  const siderContent = (
    <div className="flex h-full flex-col">
      {/* Brand header aligned to 68px topbar height */}
      <div className={`flex flex-none items-center border-0 border-b border-[var(--tcx-side-border)] ${isCollapsed ? 'justify-center px-0' : 'px-3.5'}`} style={{ height: shapeTokens.topbarHeight }}>
        <Dropdown menu={{ items: brandMenuItems }} trigger={['click']} placement="bottomLeft">
          <Tooltip
            title={
              isCollapsed ? (
                <div className="flex flex-col text-left leading-snug">
                  <span className="font-semibold text-white">TechCMantix Console</span>
                  <span className="text-[11px] text-white/75">Platform Admin</span>
                </div>
              ) : undefined
            }
            placement="right"
            styles={TOOLTIP_STYLES}
          >
            <button type="button" className={`flex w-full cursor-pointer items-center gap-3 border-0 bg-transparent text-left ${isCollapsed ? 'justify-center px-0' : 'px-0.5'}`} aria-label="Platform console menu">
              <span className="tcx-brand-mark" aria-hidden="true">
                T
              </span>
              {!isCollapsed ? (
                <>
                  <div className="min-w-0 flex-1 leading-tight">
                    <b className="block truncate text-[15.5px] font-bold leading-[1.15] tracking-[-0.01em] text-[var(--tcx-side-brand)]">TechCMantix Console</b>
                    <span className="mt-0.5 block truncate text-[10.5px] font-bold uppercase leading-[1.15] tracking-[0.1em] text-[var(--tcx-side-mute)]">Platform Admin</span>
                  </div>
                  <span className="flex-none text-[var(--tcx-side-mute)]">
                    <Icon name="chevronDown" size={15} />
                  </span>
                </>
              ) : null}
            </button>
          </Tooltip>
        </Dropdown>
      </div>

      <div className="flex flex-1 flex-col overflow-hidden px-[14px] pb-[12px] pt-2">
        <nav aria-label="Platform console navigation" className="tcx-sider-scroll flex-1 overflow-y-auto overflow-x-hidden pr-0.5">
          {PLATFORM_NAV_GROUPS.map((group) => (
            <div key={group.label} className="mb-4">
              {!isCollapsed ? <div className="px-3 pb-2 text-[10.5px] font-bold uppercase tracking-[0.1em] text-[var(--tcx-side-mute)]">{group.label}</div> : <div className="mx-3 my-2 h-px bg-[var(--tcx-side-border)]" />}

              <div className="flex flex-col">
                {group.items.map((item) => {
                  const isActive = activeRoute === item.id;
                  const badgeCount = item.id === 'p-tenants' ? organizationsCount : item.id === 'p-audit' && auditLogs.length > 0 ? auditLogs.length : null;

                  return (
                    <Tooltip key={item.id} title={isCollapsed ? item.label : undefined} placement="right" styles={TOOLTIP_STYLES}>
                      <button type="button" aria-current={isActive ? 'page' : undefined} onClick={() => handleNavClick(item.id)} className={`tcx-nav-btn ${isCollapsed ? 'justify-center px-0' : ''}`}>
                        <span className="i flex-none">
                          <Icon name={item.icon} size={18} />
                        </span>
                        {!isCollapsed ? (
                          <>
                            <span className="flex-1 truncate text-left">{item.label}</span>
                            {badgeCount !== null ? <span className="tcx-count">{badgeCount}</span> : null}
                          </>
                        ) : null}
                      </button>
                    </Tooltip>
                  );
                })}
              </div>
            </div>
          ))}
        </nav>

        {!isCollapsed ? (
          <div className="mt-auto flex flex-none flex-col gap-2 pt-3">
            <div className="tcx-plan-card">
              <b>Platform scope</b>
              <span>Manage tenant organizations, invite initial Organization Admins, and inspect audit logs.</span>
            </div>
            <div className="tcx-side-user">
              <UserAvatar name={user.name} size={36} />
              <div className="tcx-side-user-meta">
                <b>{user.name}</b>
                <span>Super administrator</span>
              </div>
              <button
                type="button"
                onClick={() => {
                  void onLogout();
                }}
                aria-label="Sign out"
                title="Sign out"
                className="tcx-side-btn grid h-[34px] w-[34px] flex-none cursor-pointer place-items-center rounded-lg border-0 bg-transparent text-[var(--tcx-side-mute)] hover:bg-[var(--tcx-side-hover)] hover:text-[var(--tcx-side-hover-text)]"
              >
                <Icon name="logout" size={17} />
              </button>
            </div>
          </div>
        ) : null}
      </div>
    </div>
  );

  return (
    <Layout style={{ minHeight: '100vh', background: 'var(--tcx-bg)' }}>
      {isMobile && mobileOpen ? <div role="presentation" onClick={() => setMobileOpen(false)} className="fixed inset-0 z-40 bg-black/50 backdrop-blur-[1px]" /> : null}

      <Sider
        width={284}
        collapsedWidth={72}
        collapsed={isCollapsed}
        trigger={null}
        style={
          isMobile
            ? {
                position: 'fixed',
                top: 0,
                left: 0,
                bottom: 0,
                zIndex: 50,
                background: 'var(--tcx-sider)',
                borderRight: '1px solid var(--tcx-side-border)',
                padding: 0,
                transform: mobileOpen ? 'translateX(0)' : 'translateX(-100%)',
                transition: 'transform 0.25s cubic-bezier(0.22, 1, 0.36, 1)',
              }
            : {
                position: 'sticky',
                top: 0,
                height: '100vh',
                background: 'var(--tcx-sider)',
                borderRight: prefs.sidebarStyle === 'light' && mode === 'light' ? '1px solid var(--tcx-border)' : 'none',
                padding: 0,
              }
        }
      >
        {siderContent}
      </Sider>

      <Layout style={{ minWidth: 0, background: 'var(--tcx-bg)' }}>
        <Header
          style={{
            position: 'sticky',
            top: 0,
            zIndex: 30,
            height: 68,
            padding: '0 28px',
            background: 'var(--tcx-surface)',
            borderBottom: '1px solid var(--tcx-border)',
            display: 'flex',
            alignItems: 'center',
            gap: 14,
          }}
        >
          <Tooltip title={isCollapsed ? 'Expand sidebar' : 'Collapse sidebar'} placement="bottom" styles={TOOLTIP_STYLES}>
            <button
              type="button"
              className="tcx-top-btn flex cursor-pointer items-center justify-center border-0 bg-transparent text-[var(--tcx-text-2)] hover:bg-[var(--tcx-sunken)]"
              aria-label={isMobile ? 'Toggle navigation menu' : isCollapsed ? 'Expand sidebar' : 'Collapse sidebar'}
              onClick={() => {
                if (isMobile) setMobileOpen((o) => !o);
                else updatePrefs({ collapsed: !collapsed });
              }}
            >
              <Icon name={isMobile ? 'menu' : 'panel'} size={18} />
            </button>
          </Tooltip>

          <button type="button" className="tcx-search" onClick={onOpenPalette} aria-label="Search or jump to (Ctrl K)">
            <Icon name="search" size={16} />
            <span className="tcx-search-lbl flex-1 text-left">Search or jump to</span>
            <kbd className="tcx-kbd">Ctrl K</kbd>
          </button>

          <div className="ml-auto flex items-center gap-5">
            <button type="button" className="tcx-top-btn flex cursor-pointer items-center justify-center border-0 bg-transparent text-[var(--tcx-muted)] hover:bg-[var(--tcx-sunken)] hover:text-[var(--tcx-text)]" onClick={toggleTheme} aria-label={mode === 'dark' ? 'Switch to light theme' : 'Switch to dark theme'} title={mode === 'dark' ? 'Switch to light theme' : 'Switch to dark theme'}>
              <Icon name={mode === 'dark' ? 'sun' : 'moon'} size={18} />
            </button>

            <Dropdown menu={{ items: notifMenuItems }} trigger={['click']} placement="bottomRight" onOpenChange={(open) => open && markAuditSeen()}>
              <button type="button" className="tcx-top-btn relative flex cursor-pointer items-center justify-center border-0 bg-transparent text-[var(--tcx-muted)] hover:bg-[var(--tcx-sunken)] hover:text-[var(--tcx-text)]" aria-label={unseenAuditCount > 0 ? `Recent platform audit events, ${unseenAuditCount} new` : 'Recent platform audit events'}>
                <Icon name="bell" size={18} />
                {unseenAuditCount > 0 ? <span className="tcx-dot-badge" /> : null}
              </button>
            </Dropdown>

            <Dropdown menu={{ items: userMenuItems }} trigger={['click']} placement="bottomRight">
              <button type="button" aria-label="Account menu" className="ml-1 flex cursor-pointer items-center rounded-full border-0 bg-transparent p-0">
                <UserAvatar name={user.name} size={38} className="tcx-avatar-ring" />
              </button>
            </Dropdown>
          </div>
        </Header>

        <Content style={{ background: 'var(--tcx-bg)' }}>
          <div className="tcx-view">{children}</div>
        </Content>
      </Layout>
    </Layout>
  );
}
