import { useCoreServices } from '@learnitive/context';
import {
  Breadcrumb,
  Button,
  buttonVariants,
  cn,
  Separator,
  Sidebar,
  StarButton,
} from '@learnitive/ui-components';
import { WsPath } from '@learnitive/ws-path';
import { useAtomValue } from 'jotai';
import { Home, Monitor, Moon, Sun, Users } from 'lucide-react';
import React from 'react';
import { CompilePanel } from '../components/compile-panel';
import { suggestedProjectFileName } from '../common/project-file-suggestion';
import { AiSettingsControl } from '../components/ai-settings-dialog';
import { GitPanel } from '../components/git-panel';
import { CollaborationDialog } from '../components/collaboration-dialog';
import { MarkdownFidelityNotice } from '../components/navigation/markdown-fidelity-notice';
import { NoteBreadcrumb } from '../components/navigation/note-breadcrumb';
import { WsNameBreadcrumb } from '../components/navigation/ws-name-breadcrumb'; // Import WsNameBreadcrumb
import { getAuthState, updateSafeSettingsIfAuthenticated, type SaasAuthState } from '../saas/saas-api';
import { LearnitiveAccountPopover } from '../components/account-popover';

export interface AppHeaderProps {
  children?: React.ReactNode;
}

/** The main application header container, holding the toolbar content and optional children. */
export function AppHeader({ children }: AppHeaderProps) {
  const [collaborationOpen, setCollaborationOpen] = React.useState(false);
  const coreServices = useCoreServices();
  const wsPaths = useAtomValue(coreServices.workspaceState.$wsPaths);
  const currentWsFilePath = useAtomValue(
    coreServices.workspaceState.$currentWsFilePath,
  );
  const currentWsName = useAtomValue(
    coreServices.workspaceState.$currentWsName,
  );
  const collaborationState = useAtomValue(coreServices.projectCollaboration.$state);
  const visibleCollaborators = collaborationState.active && collaborationState.wsName === currentWsName
    ? collaborationState.peers.slice(0, 3)
    : [];
  const showEditorToolbar = Boolean(currentWsFilePath);

  return (
    <header className="desktop-titlebar-drag desktop-titlebar-surface interactive-ws-header flex h-[var(--learnitive-app-titlebar-height)] max-h-[var(--learnitive-app-titlebar-height)] min-h-[var(--learnitive-app-titlebar-height)] shrink-0 items-center gap-2 overflow-hidden px-3">
      <div
        aria-hidden="true"
        className="desktop-titlebar-main-spacer shrink-0"
      />
      <div className="flex h-full min-w-0 flex-1 items-center gap-2">
        <ToolbarLeftSection
          showEditorToolbar={showEditorToolbar}
          currentWsPath={currentWsFilePath?.wsPath}
          currentWsName={currentWsName}
          wsPaths={wsPaths.map((wsPath) => wsPath.wsPath)}
        />
        {showEditorToolbar && currentWsName && <ToolbarRightSection />}
        {currentWsName && <CompilePanel wsName={currentWsName} />}
        <AiSettingsControl mode="trigger" />
        {currentWsName && <GitPanel wsName={currentWsName} />}
        <EditorThemeControl />
        {currentWsName && (
          <>
            <Button
              aria-label={t.app.collaboration.button}
              className="desktop-titlebar-no-drag h-7 px-2 sm:px-2.5"
              size="sm"
              title={t.app.collaboration.button}
              variant="ghost"
              onClick={() => setCollaborationOpen(true)}
            >
              {visibleCollaborators.length ? (
                <span className="flex -space-x-1.5 sm:mr-1" aria-hidden="true">
                  {visibleCollaborators.map((peer) => (
                    <span
                      key={peer.clientId}
                      className="grid size-5 place-items-center rounded-full border-2 border-background text-[9px] font-bold text-white"
                      style={{ backgroundColor: peer.color }}
                      title={peer.name}
                    >
                      {peer.name.trim().slice(0, 1).toUpperCase()}
                    </span>
                  ))}
                </span>
              ) : <Users className="size-4 sm:mr-1" />}
              <span className="hidden sm:inline">{t.app.collaboration.button}</span>
              {collaborationState.active && collaborationState.wsName === currentWsName ? (
                <span className="ml-1 rounded bg-primary/10 px-1 text-[9px] font-semibold">{collaborationState.peers.length + 1}</span>
              ) : null}
            </Button>
            <CollaborationDialog
              wsName={currentWsName}
              open={collaborationOpen}
              onOpenChange={setCollaborationOpen}
            />
          </>
        )}
        <EditorAccountControl />
      </div>
      {children ? (
        <div className="desktop-titlebar-no-drag">{children}</div>
      ) : null}
    </header>
  );
}

interface ToolbarLeftSectionProps {
  showEditorToolbar: boolean;
  currentWsPath: string | undefined;
  currentWsName: string | undefined;
  wsPaths: string[];
}

function ToolbarLeftSection({
  showEditorToolbar,
  currentWsPath,
  currentWsName,
  wsPaths,
}: ToolbarLeftSectionProps) {
  const coreServices = useCoreServices();
  const workspaces = useAtomValue(coreServices.workspaceState.$workspaces);
  const newFileName = suggestedProjectFileName(workspaces.find((item) => item.name === currentWsName)?.metadata, currentWsPath ? WsPath.fromString(currentWsPath).path : undefined);

  return (
    <div className="desktop-titlebar-no-drag flex min-w-0 flex-1 items-center gap-2">
      <Sidebar.SidebarTrigger className="-ml-1" />
      <a className="interactive-brand interactive-editor-brand" href="/projects" aria-label="Learnitive projects"><img className="interactive-brand-logo" src="/learnitive-logo-mobile.png" alt="" /><span className="interactive-brand-name">Learnitive</span></a>
      <Separator orientation="vertical" className="h-4" />
      {showEditorToolbar && currentWsPath ? (
        <>
          <NoteBreadcrumb
            wsPath={currentWsPath}
            wsPaths={wsPaths}
            onNewNote={({ wsPath }) => {
              const parent = WsPath.fromString(wsPath).getParent();
              const path = parent?.path;

              coreServices.commandDispatcher.dispatch(
                'command::ui:create-file-dialog',
                {
                  prefillName: newFileName,
                  pathPrefix: path || undefined,
                },
                'AppHeader',
              );
            }}
          />
          <div className="shrink-0">
            <MarkdownFidelityNotice wsPath={currentWsPath} />
          </div>
        </>
      ) : currentWsName ? (
        <WsNameBreadcrumb wsName={currentWsName} />
      ) : (
        <HomeBreadcrumb coreServices={coreServices} />
      )}
    </div>
  );
}

function HomeBreadcrumb({
  coreServices,
}: {
  coreServices: ReturnType<typeof useCoreServices>;
}) {
  return (
    <Breadcrumb.Breadcrumb>
      <Breadcrumb.BreadcrumbList>
        <Breadcrumb.BreadcrumbItem>
          <Breadcrumb.BreadcrumbLink
            className={cn(
              buttonVariants({ variant: 'ghost', size: 'icon' }),
              'h-7 w-7',
            )}
            href={coreServices.navigation.toUri({
              route: 'welcome',
              payload: {},
            })}
            title={t.app.common.home}
          >
            <Home size={16} />
          </Breadcrumb.BreadcrumbLink>
        </Breadcrumb.BreadcrumbItem>
      </Breadcrumb.BreadcrumbList>
    </Breadcrumb.Breadcrumb>
  );
}

function EditorThemeControl() {
  const coreServices = useCoreServices();
  const preference = useAtomValue(coreServices.workbenchState.$themePref);
  const next = preference === 'light' ? 'dark' : preference === 'dark' ? 'system' : 'light';
  const Icon = preference === 'light' ? Sun : preference === 'dark' ? Moon : Monitor;
  const label = `Theme: ${preference}. Switch to ${next}.`;
  return (
    <Button
      aria-label={label}
      className="desktop-titlebar-no-drag h-7 w-7 p-0"
      size="icon"
      title={label}
      type="button"
      variant="ghost"
      onClick={() => {
        coreServices.workbenchState.changeThemePreference(next);
        void updateSafeSettingsIfAuthenticated({ theme: next });
      }}
    >
      <Icon className="size-4" />
    </Button>
  );
}

function EditorAccountControl() {
  const [auth, setAuth] = React.useState<SaasAuthState>();
  React.useEffect(() => {
    let active = true;
    void getAuthState().then((value) => { if (active) setAuth(value); }).catch(() => {
      if (active) setAuth({ authenticated: false });
    });
    return () => { active = false; };
  }, []);
  if (!auth) return null;
  return <LearnitiveAccountPopover auth={auth} variant="editor" logoutRedirect="/" />;
}

function ToolbarRightSection() {
  const coreServices = useCoreServices();
  const isCurrentWsPathStarred = useAtomValue(
    coreServices.userActivityService.$isCurrentWsPathStarred,
  );
  const currentWsPathValue = useAtomValue(
    coreServices.workspaceState.$currentWsFilePath,
  );
  const currentWsPathString = currentWsPathValue?.wsPath;

  const handleStarClick = () => {
    coreServices.commandDispatcher.dispatch(
      'command::workspace:toggle-star',
      { wsPath: currentWsPathString },
      'AppHeader.ToolbarRightSection',
    );
  };

  return (
    <div className="desktop-titlebar-no-drag flex shrink-0 items-center">
      <StarButton
        isStarred={isCurrentWsPathStarred}
        onClick={handleStarClick}
        className="ml-2"
        disabled={!currentWsPathString}
        title={
          isCurrentWsPathStarred
            ? t.app.common.unstarItem
            : t.app.common.starItem
        }
      />
    </div>
  );
}
