import { useState, useCallback, useEffect } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import type { AuthUser } from '../../hooks/useAuth';
import { shortenUrl, prewarmScreenshot, paramsWithLanguage } from '../../lib/api';
import { copyToClipboard } from '../../lib/clipboard';
import { DownloadIcon } from './icons/DownloadIcon';
import { BookmarkIcon } from './icons/BookmarkIcon';
import { LogoIcon } from './icons/LogoIcon';
import { CheckIcon } from './icons/CheckIcon';
import { ClipboardIcon } from './icons/ClipboardIcon';
import { MenuIcon } from './icons/MenuIcon';
import { SunIcon } from './icons/SunIcon';
import { MoonIcon } from './icons/MoonIcon';
import { SpinnerIcon } from './icons/SpinnerIcon';
import UserMenu from './UserMenu';
import MobileMenu from './MobileMenu';
import LanguageDropdown from './LanguageDropdown';
import ExportMenu from './ExportMenu';

export type Page =
  | 'home'
  | 'dashboard'
  | 'learn'
  | 'pricing'
  | 'property-price-map'
  | 'postcode-property-search'
  | 'commute-property-search'
  | 'school-property-search'
  | 'postcode-checker'
  | 'birmingham-property-search'
  | 'manchester-property-search'
  | 'bristol-property-search'
  | 'data-sources'
  | 'methodology'
  | 'privacy-security'
  | 'terms'
  | 'privacy'
  | 'account'
  | 'saved'
  | 'invite';

export interface HeaderExportState {
  onExport: (options?: { postcodes?: string[] }) => void;
  exporting: boolean;
}

export const PAGE_PATHS: Record<Page, string> = {
  home: '/',
  dashboard: '/dashboard',
  learn: '/learn',
  pricing: '/pricing',
  'property-price-map': '/property-price-map',
  'postcode-property-search': '/postcode-property-search',
  'commute-property-search': '/commute-property-search',
  'school-property-search': '/school-property-search',
  'postcode-checker': '/postcode-checker',
  'birmingham-property-search': '/property-search/birmingham',
  'manchester-property-search': '/property-search/manchester',
  'bristol-property-search': '/property-search/bristol',
  'data-sources': '/data-sources',
  methodology: '/methodology',
  'privacy-security': '/privacy-security',
  terms: '/terms',
  privacy: '/privacy',
  saved: '/saved',
  account: '/account',
  invite: '/invite',
};

const DASHBOARD_TABLET_SIDEBAR_QUERY = '(min-width: 768px) and (max-width: 1023px)';

export interface EditingSearchState {
  id: string;
  name: string;
}

export default function Header({
  activePage,
  activeHash,
  onPageChange,
  theme,
  onToggleTheme,
  exportState,
  dashboardParams,
  dashboardActionsDisabled = false,
  onSaveSearch,
  savingSearch,
  editingSearch,
  onCancelEdit,
  onUpdateEdit,
  user,
  onLoginClick,
  onRegisterClick,
  onLogout,
  isMobile,
}: {
  activePage: Page;
  activeHash: string;
  onPageChange: (page: Page, hash?: string) => void;
  theme: 'light' | 'dark';
  onToggleTheme: () => void;
  exportState: HeaderExportState | null;
  dashboardParams: string;
  dashboardActionsDisabled?: boolean;
  onSaveSearch: (() => void) | null;
  savingSearch: boolean;
  editingSearch: EditingSearchState | null;
  onCancelEdit: () => void;
  onUpdateEdit: () => void;
  user: AuthUser | null;
  onLoginClick: () => void;
  onRegisterClick: () => void;
  onLogout: () => void;
  isMobile: boolean;
}) {
  const { t, i18n } = useTranslation();
  const [copied, setCopied] = useState(false);
  const [sharing, setSharing] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [exportMenuOpen, setExportMenuOpen] = useState(false);
  const [isDashboardTabletSidebarWidth, setIsDashboardTabletSidebarWidth] = useState(
    () => window.matchMedia(DASHBOARD_TABLET_SIDEBAR_QUERY).matches
  );
  const useSidebarNav = isMobile || (activePage === 'dashboard' && isDashboardTabletSidebarWidth);
  const dashboardActionsBlocked = activePage === 'dashboard' && (!user || dashboardActionsDisabled);

  useEffect(() => {
    const mql = window.matchMedia(DASHBOARD_TABLET_SIDEBAR_QUERY);
    const handler = (e: MediaQueryListEvent) => setIsDashboardTabletSidebarWidth(e.matches);
    mql.addEventListener('change', handler);
    return () => mql.removeEventListener('change', handler);
  }, []);

  // Close menu on Escape
  useEffect(() => {
    if (!menuOpen) return;
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setMenuOpen(false);
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [menuOpen]);

  // Close menu when switching away from the sidebar-capable header.
  useEffect(() => {
    if (!useSidebarNav) setMenuOpen(false);
  }, [useSidebarNav]);

  useEffect(() => {
    if (dashboardActionsBlocked) setExportMenuOpen(false);
  }, [dashboardActionsBlocked]);

  const doCopy = useCallback((text: string) => {
    copyToClipboard(text, () => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  }, []);

  const handleShare = useCallback(async () => {
    if (dashboardActionsBlocked) return;
    const params =
      activePage === 'dashboard' ? dashboardParams : window.location.search.replace(/^\?/, '');
    if (!params) {
      doCopy(window.location.href);
      return;
    }
    prewarmScreenshot(params, i18n.language);
    setSharing(true);
    try {
      const shortUrl = await shortenUrl(params, i18n.language);
      doCopy(shortUrl);
    } catch {
      doCopy(
        activePage === 'dashboard'
          ? `${window.location.origin}/dashboard?${paramsWithLanguage(params, i18n.language)}`
          : window.location.href
      );
    } finally {
      setSharing(false);
    }
  }, [activePage, dashboardActionsBlocked, dashboardParams, doCopy, i18n.language]);

  const navLink = (page: Page, e: React.MouseEvent, hash?: string) => {
    if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
    e.preventDefault();
    onPageChange(page, hash);
  };

  const tabClass = (page: Page, hash?: string) =>
    `inline-flex cursor-pointer items-center px-4 py-1.5 rounded text-sm font-medium transition-colors ${
      activePage === page &&
      (hash ? activeHash === hash : page !== 'account' || activeHash !== 'invites')
        ? 'bg-navy-700 text-white'
        : 'text-warm-300 hover:bg-navy-800 hover:text-white'
    }`;

  const showEditingBar = !isMobile && editingSearch && activePage === 'dashboard';

  return (
    <>
      <header className="relative z-50 h-12 bg-navy-900 text-white flex items-center px-4 shrink-0">
        {showEditingBar && (
          <div className="pointer-events-none absolute inset-x-0 top-0 bottom-0 flex items-center justify-center px-4">
            <div className="pointer-events-auto flex items-center gap-3 max-w-[60%]">
              <span className="text-sm text-warm-300 truncate" title={editingSearch.name}>
                <Trans
                  i18nKey="savedPage.isBeingUpdated"
                  values={{ name: editingSearch.name }}
                  components={{ strong: <strong className="font-semibold text-white" /> }}
                />
              </span>
              <button
                onClick={onCancelEdit}
                className="cursor-pointer px-3 py-1.5 rounded bg-navy-800 hover:bg-navy-700 transition-colors text-sm"
              >
                {t('common.cancel')}
              </button>
              <button
                onClick={onUpdateEdit}
                disabled={savingSearch || dashboardActionsBlocked}
                className="cursor-pointer px-3 py-1.5 rounded bg-teal-600 hover:bg-teal-700 transition-colors text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5"
              >
                {savingSearch && <SpinnerIcon className="w-4 h-4 animate-spin" />}
                {savingSearch ? t('savedPage.updating') : t('common.update')}
              </button>
            </div>
          </div>
        )}
        {/* Left: Logo + nav */}
        <div className="flex min-w-0 items-center gap-4">
          <a
            href="/"
            className="flex min-w-0 cursor-pointer items-center gap-2 hover:opacity-80 transition-opacity"
            onClick={(e) => navLink('home', e)}
          >
            <LogoIcon className="w-5 h-5 shrink-0 text-teal-400" />
            <span className="truncate whitespace-nowrap text-base font-semibold text-teal-300 sm:text-lg">
              {t('header.appName')}
            </span>
          </a>

          {/* Desktop nav */}
          {!useSidebarNav && (
            <nav className="top-menu flex items-center">
              <a
                href={PAGE_PATHS.dashboard}
                className={tabClass('dashboard')}
                onClick={(e) => navLink('dashboard', e)}
              >
                {t('header.dashboard')}
              </a>
              {user && (
                <a
                  href={`${PAGE_PATHS.account}#invites`}
                  className={tabClass('account', 'invites')}
                  onClick={(e) => navLink('account', e, 'invites')}
                >
                  {t('header.inviteFriends')}
                </a>
              )}
              <a
                href={PAGE_PATHS.learn}
                className={tabClass('learn')}
                onClick={(e) => navLink('learn', e)}
              >
                {t('header.learn')}
              </a>
              {user?.subscription !== 'licensed' && !user?.isAdmin && (
                <a
                  href={PAGE_PATHS.pricing}
                  className={tabClass('pricing')}
                  onClick={(e) => navLink('pricing', e)}
                >
                  {t('header.pricing')}
                </a>
              )}
            </nav>
          )}
        </div>

        {/* Right side */}
        <div className="ml-auto flex shrink-0 items-center gap-2">
          {/* Desktop-only dashboard actions */}
          {!useSidebarNav && activePage === 'dashboard' && user && (
            <>
              <button
                onClick={handleShare}
                disabled={sharing || dashboardActionsBlocked}
                className="flex cursor-pointer items-center gap-1.5 px-3 py-1.5 rounded bg-navy-800 hover:bg-navy-700 transition-colors text-sm disabled:cursor-not-allowed disabled:opacity-50"
              >
                {sharing ? (
                  <>
                    <SpinnerIcon className="w-4 h-4 animate-spin" />
                    {t('header.sharing')}
                  </>
                ) : copied ? (
                  <>
                    <CheckIcon className="w-4 h-4" />
                    {t('common.copied')}
                  </>
                ) : (
                  <>
                    <ClipboardIcon className="w-4 h-4" />
                    {t('common.share')}
                  </>
                )}
              </button>
              {exportState && (
                <button
                  onClick={() => setExportMenuOpen(true)}
                  disabled={exportState.exporting || dashboardActionsBlocked}
                  className="flex cursor-pointer items-center gap-1.5 px-3 py-1.5 rounded bg-navy-800 hover:bg-navy-700 transition-colors text-sm disabled:cursor-not-allowed disabled:opacity-50"
                  title={t('header.exportToExcel')}
                >
                  <DownloadIcon className="w-4 h-4" />
                  {exportState.exporting ? t('header.exporting') : t('header.exportLabel')}
                </button>
              )}
              {onSaveSearch && !editingSearch && (
                <button
                  onClick={onSaveSearch}
                  disabled={savingSearch || dashboardActionsBlocked}
                  className="flex cursor-pointer items-center gap-1.5 px-3 py-1.5 rounded bg-navy-800 hover:bg-navy-700 transition-colors text-sm disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {savingSearch ? (
                    <SpinnerIcon className="w-4 h-4 animate-spin" />
                  ) : (
                    <BookmarkIcon className="w-4 h-4" />
                  )}
                  {t('common.save')}
                </button>
              )}
            </>
          )}
          {!useSidebarNav && user && (
            <a
              href={PAGE_PATHS.saved}
              className={tabClass('saved')}
              onClick={(e) => navLink('saved', e)}
            >
              {t('header.saved')}
            </a>
          )}

          {/* Desktop-only auth */}
          {!useSidebarNav && (
            <>
              {user ? (
                <UserMenu
                  user={user}
                  theme={theme}
                  onToggleTheme={onToggleTheme}
                  onLogout={onLogout}
                  onNavigate={onPageChange}
                />
              ) : (
                <>
                  <button
                    onClick={onLoginClick}
                    className="cursor-pointer px-3 py-1.5 rounded bg-navy-800 hover:bg-navy-700 transition-colors text-sm"
                  >
                    {t('header.logIn')}
                  </button>
                  <button
                    onClick={onRegisterClick}
                    className="cursor-pointer px-3 py-1.5 rounded bg-teal-600 hover:bg-teal-700 transition-colors text-sm font-medium"
                  >
                    {t('header.createAccount')}
                  </button>
                </>
              )}
            </>
          )}

          {/* Mobile auth CTA (logged out only) */}
          {useSidebarNav && !user && (
            <button
              onClick={onRegisterClick}
              className="flex h-8 max-w-[8.5rem] shrink-0 cursor-pointer items-center justify-center truncate whitespace-nowrap rounded bg-teal-600 px-2.5 text-xs font-semibold leading-none transition-colors hover:bg-teal-700 sm:max-w-none sm:px-3 sm:text-sm"
            >
              {t('header.createAccount')}
            </button>
          )}

          {/* Language selector (desktop) */}
          {!useSidebarNav && <LanguageDropdown />}

          {/* Theme toggle (desktop, logged-out only — logged-in users use UserMenu) */}
          {!useSidebarNav && !user && (
            <button
              onClick={onToggleTheme}
              className="flex cursor-pointer items-center justify-center w-8 h-8 rounded bg-navy-800 hover:bg-navy-700 transition-colors"
              title={theme === 'light' ? t('userMenu.themeLight') : t('userMenu.themeDark')}
            >
              {theme === 'light' ? (
                <SunIcon className="w-4 h-4" />
              ) : (
                <MoonIcon className="w-4 h-4" />
              )}
            </button>
          )}

          {/* Mobile hamburger */}
          {useSidebarNav && (
            <button
              onClick={() => setMenuOpen(true)}
              className="flex cursor-pointer items-center justify-center w-10 h-10 -mr-2 rounded hover:bg-navy-800 transition-colors"
              aria-label={t('header.openMenu')}
            >
              <MenuIcon className="w-6 h-6" />
            </button>
          )}
        </div>
      </header>

      {/* Mobile slide-in menu */}
      {useSidebarNav && menuOpen && (
        <MobileMenu
          activePage={activePage}
          activeHash={activeHash}
          onPageChange={onPageChange}
          theme={theme}
          onToggleTheme={onToggleTheme}
          exportState={exportState}
          onOpenExportMenu={() => setExportMenuOpen(true)}
          dashboardActionsDisabled={dashboardActionsBlocked}
          onSaveSearch={onSaveSearch}
          savingSearch={savingSearch}
          isEditingSearch={!!editingSearch}
          user={user}
          onLoginClick={onLoginClick}
          onRegisterClick={onRegisterClick}
          onLogout={onLogout}
          onClose={() => setMenuOpen(false)}
          onShare={handleShare}
          copied={copied}
          sharing={sharing}
        />
      )}
      {/* Export menu modal (shared between desktop and mobile triggers) */}
      {exportState && (
        <ExportMenu
          open={exportMenuOpen}
          exporting={exportState.exporting}
          onClose={() => setExportMenuOpen(false)}
          onExport={(opts) => {
            setExportMenuOpen(false);
            exportState.onExport(opts);
          }}
        />
      )}
      {/* Mobile "Copied" toast */}
      {useSidebarNav && copied && (
        <div className="fixed top-14 left-1/2 -translate-x-1/2 z-[60] flex items-center gap-2 px-4 py-2 rounded-lg bg-navy-900 text-white text-sm shadow-lg animate-fade-in">
          <CheckIcon className="w-4 h-4 text-teal-400" />
          {t('common.copiedToClipboard')}
        </div>
      )}
    </>
  );
}
