'use client';

import React, { useEffect, useMemo, useState } from 'react';
import { signOut } from 'next-auth/react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import {
  Activity,
  ChevronRight,
  ExternalLink,
  Home,
  PlusCircle,
  Settings,
  Sparkles,
  User,
} from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from '@alga-psa/ui/components/DropdownMenu';
import { Button } from '@alga-psa/ui/components/Button';
import UserAvatar from '@alga-psa/ui/components/UserAvatar';
import ContactAvatar from '@alga-psa/ui/components/ContactAvatar';
import { NotificationBell } from '@alga-psa/notifications/components';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';
import type { IUserWithRoles } from '@alga-psa/types';
import { menuItems, bottomMenuItems, MenuItem } from '@/config/menuConfig';
import { getCurrentUser } from '@alga-psa/user-composition/actions';
import { useUserAvatar, useContactAvatar } from '@alga-psa/user-composition/hooks';
import { checkAccountManagementPermission } from '@alga-psa/auth/actions';
import { isSelfHostLicensingAction } from '@alga-psa/licensing/actions';
import { NINEMINDS_PORTAL_URL } from '@/lib/ninemindsPortal';
import type { JobMetrics } from '@alga-psa/jobs/actions';
import { getQueueMetricsAction } from '@alga-psa/jobs/actions';
import { analytics } from '@alga-psa/analytics/client';
import { QuickCreateDialog, QuickCreateType } from './QuickCreateDialog';
import { useProduct } from '@/context/ProductContext';
import { ThemeToggle } from '@alga-psa/ui/components/ThemeToggle';
import { TrialBanner } from './TrialBanner';
import { PaymentFailedBanner } from './PaymentFailedBanner';
import { useQuickAsk } from './QuickAskContext';
import { useCatalogShortcut, useShortcutScope } from '@alga-psa/ui/keyboard-shortcuts';

export const QUICK_CREATE_OPEN_EVENT = 'alga:quick-create:open';

interface HeaderProps {
  sidebarOpen: boolean;
  setSidebarOpen: React.Dispatch<React.SetStateAction<boolean>>;
  rightSidebarOpen: boolean;
  setRightSidebarOpen: React.Dispatch<React.SetStateAction<boolean>>;
}

interface QuickCreateOption {
  id: string;
  labelKey: string;
  labelDefault: string;
  descriptionKey: string;
  descriptionDefault: string;
  label: string;
  description: string;
  type: QuickCreateType;
}

const quickCreateOptions: QuickCreateOption[] = [
  {
    id: 'create-ticket',
    labelKey: 'header.quickCreate.options.ticket.label',
    labelDefault: 'Ticket',
    descriptionKey: 'header.quickCreate.options.ticket.description',
    descriptionDefault: 'Create a new support ticket',
    label: 'Ticket',
    description: 'Create a new support ticket',
    type: 'ticket'
  },
  {
    id: 'create-client',
    labelKey: 'header.quickCreate.options.client.label',
    labelDefault: 'Client',
    descriptionKey: 'header.quickCreate.options.client.description',
    descriptionDefault: 'Add a new client to your system',
    label: 'Client',
    description: 'Add a new client to your system',
    type: 'client'
  },
  {
    id: 'create-contact',
    labelKey: 'header.quickCreate.options.contact.label',
    labelDefault: 'Contact',
    descriptionKey: 'header.quickCreate.options.contact.description',
    descriptionDefault: 'Add a new contact person',
    label: 'Contact',
    description: 'Add a new contact person',
    type: 'contact'
  },
  {
    id: 'create-project',
    labelKey: 'header.quickCreate.options.project.label',
    labelDefault: 'Project',
    descriptionKey: 'header.quickCreate.options.project.description',
    descriptionDefault: 'Start a new project',
    label: 'Project',
    description: 'Start a new project',
    type: 'project'
  },
  {
    id: 'create-asset',
    labelKey: 'header.quickCreate.options.asset.label',
    labelDefault: 'Asset',
    descriptionKey: 'header.quickCreate.options.asset.description',
    descriptionDefault: 'Add a new device to your workspace',
    label: 'Asset',
    description: 'Add a new device to your workspace',
    type: 'asset'
  },
  {
    id: 'create-service',
    labelKey: 'header.quickCreate.options.service.label',
    labelDefault: 'Service',
    descriptionKey: 'header.quickCreate.options.service.description',
    descriptionDefault: 'Add a new billable service',
    label: 'Service',
    description: 'Add a new billable service',
    type: 'service'
  },
  {
    id: 'create-product',
    labelKey: 'header.quickCreate.options.product.label',
    labelDefault: 'Product',
    descriptionKey: 'header.quickCreate.options.product.description',
    descriptionDefault: 'Add a new product to your catalog',
    label: 'Product',
    description: 'Add a new product to your catalog',
    type: 'product'
  }
];

type HeaderTranslator = (key: string, options?: Record<string, unknown>) => string;

const getMenuItemNameByPath = (
  path: string | null | undefined,
  t: HeaderTranslator,
): string => {
  if (!path) {
    return t('header.breadcrumb.dashboard', { defaultValue: 'Dashboard' });
  }

  const allMenuItems = [...menuItems, ...bottomMenuItems];

  const segments = path.split('/');
  const topLevelPath = segments.length > 1 ? '/' + segments[1] : '/';

  const findMenuItem = (items: MenuItem[]): string | null => {
    for (const item of items) {
      if (item.href === topLevelPath || (item.href && path.startsWith(item.href))) {
        return item.translationKey
          ? t(item.translationKey, { defaultValue: item.name })
          : item.name;
      }
      if (item.subItems) {
        const subItemName = findMenuItem(item.subItems);
        if (subItemName) return subItemName;
      }
    }
    return null;
  };

  return findMenuItem(allMenuItems) || t('header.breadcrumb.dashboard', { defaultValue: 'Dashboard' });
};

const TenantBadge: React.FC<{
  tenant?: string | null;
  ariaLabel: string;
}> = ({ tenant, ariaLabel }) => {
  if (!tenant) {
    return null;
  }

  return (
    <span
      className="inline-flex items-center rounded-full bg-slate-100 dark:bg-[rgb(var(--color-border-100))] px-3 py-1 text-xs font-medium text-slate-700 dark:text-[rgb(var(--color-text-400))] border border-slate-200 dark:border-[rgb(var(--color-border-200))]"
      aria-label={ariaLabel}
    >
      {tenant}
    </span>
  );
};

const ALGADESK_QUICK_CREATE_TYPES: ReadonlySet<QuickCreateType> = new Set([
  'ticket',
  'client',
  'contact',
]);

const QuickCreateMenu: React.FC<{ t: HeaderTranslator }> = ({ t }) => {
  const [activeQuickCreate, setActiveQuickCreate] = useState<QuickCreateType>(null);
  const [menuOpen, setMenuOpen] = useState(false);
  const { isAlgaDesk } = useProduct();
  const visibleOptions = isAlgaDesk
    ? quickCreateOptions.filter((option) => ALGADESK_QUICK_CREATE_TYPES.has(option.type))
    : quickCreateOptions;
  const translatedOptions = visibleOptions.map((option) => ({
    ...option,
    label: t(option.labelKey, { defaultValue: option.labelDefault }),
    description: t(option.descriptionKey, { defaultValue: option.descriptionDefault }),
  }));

  const handleQuickCreateSelect = (type: QuickCreateType) => {
    analytics.capture('ui.quick_create.select', { target: type });
    setMenuOpen(false);
    setActiveQuickCreate(type);
  };

  useEffect(() => {
    const openMenu = () => {
      setMenuOpen(true);
    };

    window.addEventListener(QUICK_CREATE_OPEN_EVENT, openMenu);
    return () => window.removeEventListener(QUICK_CREATE_OPEN_EVENT, openMenu);
  }, []);
  useShortcutScope('page');
  useCatalogShortcut('global.quickCreate', () => {
    setMenuOpen(true);
  }, { enabled: translatedOptions.length > 0 });

  return (
    <>
      <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
        <DropdownMenuTrigger asChild>
          <Button
            id="global-quick-create-trigger"
            variant="ghost"
            size="sm"
            className="flex items-center gap-2"
            aria-label={t('header.quickCreate.ariaLabel', { defaultValue: 'Open quick create' })}
          >
            <PlusCircle className="h-5 w-5" />
            <span className="hidden lg:inline text-sm font-medium">
              {t('header.quickCreate.title', { defaultValue: 'Quick Create' })}
            </span>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-64">
          <div className="px-3 py-2">
            <p className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
              {t('header.quickCreate.heading', { defaultValue: 'Create' })}
            </p>
          </div>
          {translatedOptions.map((option) => (
            <DropdownMenuItem
              key={option.id}
              id={`${option.id}-menu-item`}
              onSelect={() => handleQuickCreateSelect(option.type)}
              className="flex flex-col items-start gap-0.5"
            >
              <span className="text-sm font-medium text-gray-900">{option.label}</span>
              <span className="text-xs text-gray-500">{option.description}</span>
            </DropdownMenuItem>
          ))}
        </DropdownMenuContent>
      </DropdownMenu>
      
      {activeQuickCreate && (
        <QuickCreateDialog
          type={activeQuickCreate}
          onClose={() => setActiveQuickCreate(null)}
        />
      )}
    </>
  );
};

// NotificationMenu component removed - replaced with NotificationBell

const JobActivityIndicator: React.FC<{ t: HeaderTranslator }> = ({ t }) => {
  const router = useRouter();
  const [metrics, setMetrics] = useState<JobMetrics | null>(null);
  const [loading, setLoading] = useState<boolean>(false);

  useEffect(() => {
    let isMounted = true;
    let interval: ReturnType<typeof setInterval> | undefined;

    const fetchMetrics = async () => {
      setLoading(true);
      try {
        const data = await getQueueMetricsAction();
        if (isMounted) {
          setMetrics(data);
        }
      } catch (error) {
        console.error('[Header] Failed to fetch job metrics', error);
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    };

    fetchMetrics();
    interval = setInterval(fetchMetrics, 15000);

    return () => {
      isMounted = false;
      if (interval) {
        clearInterval(interval);
      }
    };
  }, []);

  const activeJobs = metrics?.active ?? 0;
  const failedJobs = metrics?.failed ?? 0;
  const hasAttention = failedJobs > 0;

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          id="job-activity-trigger"
          variant="ghost"
          size="icon"
          aria-label={t('header.jobs.ariaLabel', { defaultValue: 'View background job activity' })}
          className="relative h-9 w-9"
        >
          <Activity className={`h-5 w-5 ${hasAttention ? 'text-amber-600' : 'text-gray-600'}`} />
          {(activeJobs > 0 || failedJobs > 0) && (
            <span className={`absolute right-1 top-1 inline-flex h-2.5 w-2.5 rounded-full ${failedJobs > 0 ? 'bg-amber-500' : 'bg-emerald-500'}`} />
          )}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-72">
        <div className="px-3 py-2">
          <p className="text-sm font-semibold text-gray-900">
            {t('header.jobs.title', { defaultValue: 'Background Jobs' })}
          </p>
          <p className="text-xs text-gray-500">
            {t('header.jobs.description', {
              defaultValue: 'Track imports, automation runs, and scheduled work.',
            })}
          </p>
        </div>
        <DropdownMenuSeparator />
        <div className="px-3 py-2 space-y-2">
          <div className="flex items-center justify-between text-sm">
            <span className="text-gray-600">
              {t('header.jobs.active', { defaultValue: 'Active jobs' })}
            </span>
            <span className="font-medium text-gray-900">{loading ? '—' : activeJobs}</span>
          </div>
          <div className="flex items-center justify-between text-sm">
            <span className="text-gray-600">
              {t('header.jobs.queued', { defaultValue: 'Queued jobs' })}
            </span>
            <span className="font-medium text-gray-900">{loading ? '—' : metrics?.queued ?? 0}</span>
          </div>
          <div className="flex items-center justify-between text-sm">
            <span className="text-gray-600">
              {t('header.jobs.failedLast24h', { defaultValue: 'Failed last 24h' })}
            </span>
            <span className={`font-medium ${failedJobs > 0 ? 'text-amber-600' : 'text-gray-900'}`}>{loading ? '—' : failedJobs}</span>
          </div>
        </div>
        <DropdownMenuSeparator />
        <DropdownMenuItem
          id="open-job-center-menu-item"
          onSelect={() => {
            analytics.capture('ui.job_center.opened');
            router.push('/msp/jobs');
          }}
        >
          {t('header.jobs.openJobCenter', { defaultValue: 'Open Job Center' })}
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
};

export default function Header({
  sidebarOpen,
  setSidebarOpen,
  rightSidebarOpen: _rightSidebarOpen,
  setRightSidebarOpen: _setRightSidebarOpen,
}: HeaderProps) {
  const { t } = useTranslation('msp/core');
  const [userData, setUserData] = useState<IUserWithRoles | null>(null);
  const [canManageAccount, setCanManageAccount] = useState<boolean>(false);
  // Self-host/on-prem installs manage billing via the Nine Minds client portal,
  // not the in-app Stripe account page.
  const [isOnPrem, setIsOnPrem] = useState<boolean>(false);
  const router = useRouter();
  const { aiAssistantAvailable, openQuickAsk } = useQuickAsk();

  // Use SWR hooks for avatar - only one will be active based on user type
  const { avatarUrl: userAvatarUrl } = useUserAvatar(
    userData?.user_type !== 'client' ? userData?.user_id : undefined,
    userData?.user_type !== 'client' ? userData?.tenant : undefined
  );
  const { avatarUrl: contactAvatarUrl } = useContactAvatar(
    userData?.user_type === 'client' ? userData?.contact_id ?? undefined : undefined,
    userData?.user_type === 'client' ? userData?.tenant : undefined
  );

  // Select the appropriate avatar URL based on user type
  const avatarUrl = userData?.user_type === 'client' ? contactAvatarUrl : userAvatarUrl;

  useEffect(() => {
    const fetchUserData = async () => {
      const user = await getCurrentUser();
      if (user) {
        setUserData(user);

        const [hasAccountPermission, onPrem] = await Promise.all([
          checkAccountManagementPermission(),
          isSelfHostLicensingAction(),
        ]);
        setCanManageAccount(hasAccountPermission);
        setIsOnPrem(onPrem);
      }
    };

    fetchUserData();
  }, []);

  const handleSignOut = () => {
    signOut({ callbackUrl: '/auth/signin', redirect: true });
  };

  const getBreadcrumbItems = (path: string | null | undefined): { name: string; href: string }[] => {
    const homeLabel = t('header.breadcrumb.home', { defaultValue: 'Home' });
    const breadcrumbs = [
      {
        name: homeLabel,
        href: '/'
      }
    ];

    if (path && path !== '/') {
      const menuName = getMenuItemNameByPath(path, t);
      breadcrumbs.push({
        name: menuName,
        href: '#'
      });
    }

    return breadcrumbs;
  };

  const pathname = usePathname();
  const showWorkflowQuickAsk = aiAssistantAvailable && Boolean(pathname?.startsWith('/msp/workflow-editor'));
  const handleWorkflowQuickAskOpen = () => {
    analytics.capture('ui.workflow_designer.quick_ask.opened', { source: 'header' });
    openQuickAsk();
  };
  const breadcrumbItems = useMemo(() => getBreadcrumbItems(pathname), [pathname, t]);
  const homeLabel = t('header.breadcrumb.home', { defaultValue: 'Home' });
  const tenantBadgeAriaLabel = userData?.tenant
    ? t('header.tenantBadge.ariaLabel', {
        defaultValue: 'Active tenant {{tenant}}',
        tenant: userData.tenant,
      })
    : '';

  return (
    <header className="flex items-center justify-between border-b border-[rgb(var(--color-border-200))] bg-[rgb(var(--color-card))] px-4 py-3 shadow-sm">
      <div className="flex items-center gap-3">
        <nav aria-label={t('header.breadcrumb.label', { defaultValue: 'Breadcrumb' })}>
          <ol className="flex items-center space-x-2">
            {breadcrumbItems.map((item, index) => (
              <li key={`${item.href}-${index}`} className="flex items-center">
                {index > 0 && (
                  <ChevronRight className="w-4 h-4 mx-2 text-[rgb(var(--color-text-400))]" />
                )}
                {index === 0 ? (
                  <Link
                    prefetch={false}
                    href={item.href}
                    className="text-gray-500 hover:text-main-800 text-md transition-colors cursor-pointer"
                    aria-label={homeLabel}
                  >
                    <Home className="w-5 h-5" />
                    <span className="sr-only">{homeLabel}</span>
                  </Link>
                ) : index === breadcrumbItems.length - 1 ? (
                  <span className="text-xl font-semibold text-main-800">
                    {item.name}
                  </span>
                ) : (
                  <Link
                    prefetch={false}
                    href={item.href}
                    className="text-md text-gray-500 hover:text-main-800 transition-colors cursor-pointer"
                  >
                    {item.name}
                  </Link>
                )}
              </li>
            ))}
          </ol>
        </nav>
      </div>

      <div className="flex items-center gap-3">
        <PaymentFailedBanner />
        <TrialBanner />
        <TenantBadge tenant={userData?.tenant} ariaLabel={tenantBadgeAriaLabel} />
        {showWorkflowQuickAsk ? (
          <button
            id="workflow-designer-ask-ai"
            type="button"
            className="inline-flex items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-purple-700 transition-colors hover:bg-purple-50 hover:text-purple-900 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2 dark:text-purple-300 dark:hover:bg-purple-950/30 dark:hover:text-purple-200"
            aria-label={t('header.quickAsk.ariaLabel', { defaultValue: 'Ask AI about this workflow' })}
            title={t('header.quickAsk.shortcutHint', { defaultValue: 'Open Quick Ask for workflow guidance' })}
            onClick={handleWorkflowQuickAskOpen}
          >
            <Sparkles className="h-5 w-5" />
            <span className="hidden lg:inline">{t('header.quickAsk.title', { defaultValue: 'Ask AI' })}</span>
          </button>
        ) : null}
        <QuickCreateMenu t={t} />
        <ThemeToggle
          labels={{
            ariaLabel: t('header.themeToggle.ariaLabel', { defaultValue: 'Theme toggle' }),
            light: t('header.themeToggle.light', { defaultValue: 'Light' }),
            dark: t('header.themeToggle.dark', { defaultValue: 'Dark' }),
            system: t('header.themeToggle.system', { defaultValue: 'System' }),
            selected: t('header.themeToggle.selected', { defaultValue: 'Selected' }),
          }}
        />
        <NotificationBell />
        <JobActivityIndicator t={t} />
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              id="user-menu-trigger"
              variant="ghost"
              size="icon"
              aria-label={t('header.openUserMenu')}
              className="relative h-10 w-10 rounded-full"
            >
              {userData?.user_type === 'client' ? (
                <ContactAvatar
                  contactId={userData?.contact_id || ''}
                  contactName={`${userData?.first_name || ''} ${userData?.last_name || ''}`}
                  avatarUrl={avatarUrl}
                  size="sm"
                />
              ) : (
                <UserAvatar
                  userId={userData?.user_id || ''}
                  userName={`${userData?.first_name || ''} ${userData?.last_name || ''}`}
                  avatarUrl={avatarUrl}
                  size="sm"
                />
              )}
              <span className="absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 bg-green-500 rounded-full border-2 border-[rgb(var(--color-card))]" />
            </Button>
          </DropdownMenuTrigger>

          <DropdownMenuContent align="end" className="min-w-[220px]">
            <div className="px-3 py-2">
              <p className="text-sm font-semibold text-[rgb(var(--color-text-900))]">
                {userData
                  ? `${userData.first_name ?? ''} ${userData.last_name ?? ''}`.trim()
                  : t('header.userFallback', { defaultValue: 'User' })}
              </p>
              <p className="text-xs text-[rgb(var(--color-text-500))]">
                {t('header.quickAccess', { defaultValue: 'Quick access to profile & account.' })}
              </p>
            </div>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              id="user-profile-menu-item"
              onSelect={() => router.push(userData?.user_type === 'client' ? '/client/profile' : '/msp/profile')}
            >
              <User className="mr-2 h-4 w-4" />
              {t('header.profile', { defaultValue: 'Profile' })}
            </DropdownMenuItem>
            {canManageAccount && (
              <DropdownMenuItem
                id="user-account-menu-item"
                onSelect={() =>
                  isOnPrem
                    ? window.open(NINEMINDS_PORTAL_URL, '_blank', 'noopener,noreferrer')
                    : router.push('/msp/account')
                }
              >
                <Settings className="mr-2 h-4 w-4" />
                {t('header.account', { defaultValue: 'Account' })}
                {isOnPrem && <ExternalLink className="ml-2 h-3 w-3 opacity-60" />}
              </DropdownMenuItem>
            )}
            <DropdownMenuSeparator />
            <DropdownMenuItem
              id="user-sign-out-menu-item"
              onSelect={handleSignOut}
            >
              {t('header.signOut', { defaultValue: 'Sign out' })}
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </header>
  );
}
