'use client';

import { type ReactNode, createContext, useContext, useEffect, useState } from 'react';

import { useTranslations } from 'next-intl';
import { useParams } from 'next/navigation';

import { LogOut, PencilLine, RefreshCw } from 'lucide-react';
import { createPortal } from 'react-dom';

import { markSignedOut } from '@/services/auth';

import { Button } from '@/components/ui/button';
import { RouteLink } from '@/components/ui/route-link';
import { useToast } from '@/hooks/use-toast';

import { appLocales } from '@/config/i18n';
import { useAuth } from '@/contexts/AuthContext';
import { useLocaleSwitchOverrides } from '@/contexts/LocaleSwitchContext';
import { usePathname } from '@/i18n/navigation';

type AdminToolbarProps = {
  editHref: string | null;
  entityLabel: string;
};

const AdminToolbarContext = createContext<((details: AdminToolbarProps | null) => void) | null>(
  null
);

export function AdminToolbarProvider({ children }: { children: ReactNode }) {
  const [details, setDetails] = useState<AdminToolbarProps | null>(null);

  return (
    <AdminToolbarContext.Provider value={setDetails}>
      <AdminToolbar editHref={details?.editHref ?? null} entityLabel={details?.entityLabel ?? ''} />
      {children}
    </AdminToolbarContext.Provider>
  );
}

// Pages only register their optional editing controls; the shared layout owns the toolbar.
export function AdminToolbarPage({ editHref, entityLabel }: AdminToolbarProps) {
  const setDetails = useContext(AdminToolbarContext);

  useEffect(() => {
    if (!setDetails) return;
    setDetails({ editHref, entityLabel });
    return () => setDetails(null);
  }, [editHref, entityLabel, setDetails]);

  return null;
}

// `revalidatePath` matches the route file path that next-intl rewrites to
// (`/hu/alkoto/AL1`, `/en/alkoto/AL1`), not the localized URL in the address bar.
function toRoutePath(locale: string, pathname: string, params: Record<string, unknown> = {}) {
  const filled = pathname.replace(/\[(?:\.\.\.)?(\w+)\]/g, (_, key: string) => {
    const value = params[key];
    return Array.isArray(value) ? value.join('/') : String(value ?? '');
  });
  return `/${locale}${filled === '/' ? '' : filled}`;
}

function AdminToolbar({ editHref, entityLabel }: AdminToolbarProps) {
  const { isAdmin, isLoading } = useAuth();
  // Internal pathname template (e.g. `/alkoto/[id]/eletrajz`) and its params.
  const pathname = usePathname();
  const params = useParams();
  const localeSwitchOverrides = useLocaleSwitchOverrides();
  const t = useTranslations('adminToolbar');
  const tCommon = useTranslations('common');
  const { toast } = useToast();
  const [isRefreshing, setIsRefreshing] = useState(false);
  const isVisible = !isLoading && isAdmin;

  useEffect(() => {
    if (!isVisible) return;

    document.documentElement.style.setProperty('--admin-h', '36px');
    window.dispatchEvent(new Event('resize'));

    return () => {
      document.documentElement.style.setProperty('--admin-h', '0px');
      window.dispatchEvent(new Event('resize'));
    };
  }, [isVisible]);

  const handleRevalidate = async () => {
    if (isRefreshing) return;
    setIsRefreshing(true);

    try {
      const response = await fetch('/api/revalidate-path', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        // Refresh this page in every language; slug-localized pages register their
        // per-locale target in the locale switch overrides.
        body: JSON.stringify({
          paths: appLocales.map((locale) => {
            const override = localeSwitchOverrides?.[locale];
            return override
              ? toRoutePath(locale, override.pathname, override.params)
              : toRoutePath(locale, pathname, params);
          }),
        }),
      });
      if (!response.ok) {
        throw new Error(`Revalidation failed with HTTP ${response.status}`);
      }
      const data = await response.json();

      if (data?.revalidated !== true) {
        throw new Error('Revalidation was not confirmed by the server');
      }
      // Keep the button disabled until the new document loads.
      window.location.reload();
    } catch (error) {
      console.error('Revalidation error:', error);
      toast({
        variant: 'destructive',
        title: t('refreshErrorTitle'),
        description: t('refreshErrorMessage'),
      });
      setIsRefreshing(false);
    }
  };

  const handleLogout = async () => {
    try {
      await fetch('/api/logout', { method: 'POST' });
    } catch (error) {
      console.error('Logout error:', error);
    }
    markSignedOut();
    window.location.reload();
  };

  if (!isVisible) return null;

  return createPortal(
    <aside className="fixed inset-x-0 top-0 z-[60] h-9 border-b border-mma-yellow/50 bg-[#151720] text-white shadow-sm">
      <div className="mx-auto flex h-full max-w-boxed items-center justify-between gap-3 px-site">
        <div className="flex min-w-0 items-center gap-2 text-xs">
          <Button
            type="button"
            size="xs"
            variant="quiet"
            inverted
            className="w-7 px-0"
            aria-label={tCommon('refresh')}
            title={tCommon('refresh')}
            disabled={isRefreshing}
            onClick={handleRevalidate}
          >
            <RefreshCw aria-hidden="true" className={isRefreshing ? 'animate-spin' : undefined} />
          </Button>
          {entityLabel && (
            <>
              <span aria-hidden="true" className="hidden h-4 w-px bg-white/20 sm:block" />
              <span className="hidden truncate text-white/90 sm:block">{entityLabel}</span>
            </>
          )}
        </div>

        <div className="flex shrink-0 items-center gap-1.5">
          {editHref && (
            <Button asChild size="xs" inverted className="shadow-none">
              <RouteLink href={editHref} aria-label={t('edit', { name: entityLabel })}>
                <PencilLine aria-hidden="true" />
                <span className="hidden md:inline">{t('edit')}</span>
              </RouteLink>
            </Button>
          )}
          <Button type="button" size="xs" variant="quiet" inverted onClick={handleLogout}>
            <LogOut aria-hidden="true" />
            <span className="hidden md:inline">{t('logout')}</span>
          </Button>
        </div>
      </div>
    </aside>,
    document.body
  );
}
