'use client';

import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { App as AntdApp, ConfigProvider, theme as antdTheme } from 'antd';
import { AntdRegistry } from '@ant-design/nextjs-registry';
import { usePathname } from 'next/navigation';
import { APPEARANCE_STORAGE_KEY, DEFAULT_APPEARANCE, FONT_PRESETS, FONT_SCALE_PX, PUBLIC_THEME_PATHS, RADIUS_PRESETS, resolveAccentColors, resolveSidebarPalette, shapeTokens, SURFACE_TONES, THEME_STORAGE_KEY, themeTokens, type AppearancePrefs, type ThemeMode } from '../theme/tokens';

interface ThemeContextType {
  mode: ThemeMode;
  prefs: AppearancePrefs;
  primaryColor: string;
  updatePrefs: (patch: Partial<AppearancePrefs>) => void;
  resetPrefs: () => void;
  toggleTheme: () => void;
}

const ThemeContext = createContext<ThemeContextType>({
  mode: 'light',
  prefs: DEFAULT_APPEARANCE,
  primaryColor: '#C91C00',
  updatePrefs: () => {},
  resetPrefs: () => {},
  toggleTheme: () => {},
});

const PUBLIC_APPEARANCE: AppearancePrefs = { ...DEFAULT_APPEARANCE, theme: 'light' };

export const useAppTheme = () => useContext(ThemeContext);

function readStoredPrefs(): AppearancePrefs {
  if (typeof window === 'undefined') return DEFAULT_APPEARANCE;
  try {
    const raw = localStorage.getItem(APPEARANCE_STORAGE_KEY);
    if (raw) {
      const parsed = JSON.parse(raw) as Partial<AppearancePrefs>;
      return { ...DEFAULT_APPEARANCE, ...parsed };
    }
    const legacy = localStorage.getItem(THEME_STORAGE_KEY);
    if (legacy === 'light' || legacy === 'dark') {
      return { ...DEFAULT_APPEARANCE, theme: legacy };
    }
  } catch {}
  return DEFAULT_APPEARANCE;
}

function getSystemMode(): ThemeMode {
  if (typeof window === 'undefined') return 'light';
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [prefs, setPrefs] = useState<AppearancePrefs>(() => readStoredPrefs());
  const [systemMode, setSystemMode] = useState<ThemeMode>(() => getSystemMode());
  const [hydrated, setHydrated] = useState(false);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setHydrated(true);

    const mq = window.matchMedia('(prefers-color-scheme: dark)');
    const onChange = (e: MediaQueryListEvent) => setSystemMode(e.matches ? 'dark' : 'light');
    mq.addEventListener?.('change', onChange);
    return () => mq.removeEventListener?.('change', onChange);
  }, []);

  const pathname = usePathname();
  const isPublicPage = PUBLIC_THEME_PATHS.includes(pathname ?? '');
  const activePrefs = isPublicPage ? PUBLIC_APPEARANCE : prefs;
  const mode: ThemeMode = activePrefs.theme === 'system' ? systemMode : activePrefs.theme;

  const resolvedAccent = useMemo(() => resolveAccentColors(activePrefs.accent, activePrefs.customColor, mode), [activePrefs.accent, activePrefs.customColor, mode]);

  const resolvedSidebar = useMemo(() => resolveSidebarPalette(activePrefs.sidebarStyle, mode, resolvedAccent.primary), [activePrefs.sidebarStyle, mode, resolvedAccent.primary]);

  const resolvedSurface = SURFACE_TONES[activePrefs.surfaceTone][mode];
  const resolvedRadius = RADIUS_PRESETS[activePrefs.radius];
  const resolvedFont = FONT_PRESETS[activePrefs.fontFamily];
  const resolvedFontSize = FONT_SCALE_PX[activePrefs.fontScale];

  useEffect(() => {
    if (!hydrated) return;
    const root = document.documentElement;
    root.classList.toggle('dark', mode === 'dark');
    root.dataset.theme = mode;
    root.dataset.accent = activePrefs.accent;
    root.dataset.sidebar = activePrefs.sidebarStyle;
    root.dataset.radius = activePrefs.radius;
    root.dataset.font = activePrefs.fontFamily;
    root.dataset.scale = activePrefs.fontScale;
    root.dataset.surface = activePrefs.surfaceTone;

    root.style.setProperty('--tcx-primary', resolvedAccent.primary);
    root.style.setProperty('--tcx-primary-hover', resolvedAccent.hover);
    root.style.setProperty('--tcx-primary-soft', resolvedAccent.soft);
    root.style.setProperty('--tcx-primary-text', resolvedAccent.text);
    root.style.setProperty('--tcx-primary-glow', resolvedAccent.glow);
    root.style.setProperty('--tcx-primary-glow-strong', resolvedAccent.glowStrong);
    root.style.setProperty('--tcx-on-primary', resolvedAccent.onAccent);

    root.style.setProperty('--tcx-sider', resolvedSidebar.bg);
    root.style.setProperty('--tcx-side-text', resolvedSidebar.text);
    root.style.setProperty('--tcx-side-mute', resolvedSidebar.mute);
    root.style.setProperty('--tcx-side-icon', resolvedSidebar.icon);
    root.style.setProperty('--tcx-side-brand', resolvedSidebar.brand);
    root.style.setProperty('--tcx-side-border', resolvedSidebar.border);
    root.style.setProperty('--tcx-side-hover', resolvedSidebar.hoverBg);
    root.style.setProperty('--tcx-side-hover-text', resolvedSidebar.hoverText);

    root.style.setProperty('--tcx-font', resolvedFont);
    root.style.setProperty('--tcx-font-size', `${resolvedFontSize}px`);
    root.style.setProperty('--tcx-radius-sm', `${resolvedRadius.sm}px`);
    root.style.setProperty('--tcx-radius-control', `${resolvedRadius.control}px`);
    root.style.setProperty('--tcx-radius-card', `${resolvedRadius.card}px`);
    root.style.setProperty('--tcx-radius-modal', `${resolvedRadius.modal}px`);
  }, [hydrated, mode, activePrefs, resolvedAccent, resolvedSidebar, resolvedFont, resolvedFontSize, resolvedRadius]);

  const persistPrefs = useCallback((next: AppearancePrefs) => {
    try {
      localStorage.setItem(APPEARANCE_STORAGE_KEY, JSON.stringify(next));
      if (next.theme === 'light' || next.theme === 'dark') {
        localStorage.setItem(THEME_STORAGE_KEY, next.theme);
      } else {
        localStorage.removeItem(THEME_STORAGE_KEY);
      }
    } catch {}
  }, []);

  const updatePrefs = useCallback(
    (patch: Partial<AppearancePrefs>) => {
      setPrefs((prev) => {
        const next = { ...prev, ...patch };
        persistPrefs(next);
        return next;
      });
    },
    [persistPrefs],
  );

  const resetPrefs = useCallback(() => {
    setPrefs(DEFAULT_APPEARANCE);
    persistPrefs(DEFAULT_APPEARANCE);
  }, [persistPrefs]);

  const toggleTheme = useCallback(() => {
    setPrefs((prev) => {
      const current = prev.theme === 'system' ? systemMode : prev.theme;
      const nextTheme: ThemeMode = current === 'light' ? 'dark' : 'light';
      const next = { ...prev, theme: nextTheme };
      persistPrefs(next);
      return next;
    });
  }, [systemMode, persistPrefs]);

  const t = themeTokens[mode];
  const controlHeight = shapeTokens.controlHeight;
  const controlHeightSM = shapeTokens.controlHeightSM;

  return (
    <ThemeContext.Provider value={{ mode, prefs, primaryColor: resolvedAccent.primary, updatePrefs, resetPrefs, toggleTheme }}>
      <AntdRegistry layer>
        <ConfigProvider
          theme={{
            cssVar: {},
            algorithm: mode === 'dark' ? antdTheme.darkAlgorithm : antdTheme.defaultAlgorithm,
            token: {
              colorPrimary: resolvedAccent.primary,
              colorPrimaryHover: resolvedAccent.hover,
              colorInfo: resolvedAccent.primary,
              colorLink: resolvedAccent.primary,
              colorBgLayout: resolvedSurface.bg,
              colorBgContainer: resolvedSurface.surface,
              colorText: activePrefs.surfaceTone === 'contrast' ? (mode === 'dark' ? '#F8FAFC' : '#020617') : t.colorText,
              colorTextSecondary: t.colorTextSecondary,
              colorBorder: resolvedSurface.borderStrong,
              colorBorderSecondary: resolvedSurface.border,
              colorSplit: resolvedSurface.border,
              colorSuccess: t.colorSuccess,
              colorError: t.colorError,
              colorWarning: t.colorWarning,
              fontFamily: resolvedFont,
              fontSize: resolvedFontSize,
              borderRadius: resolvedRadius.control,
              borderRadiusSM: resolvedRadius.sm,
              borderRadiusLG: resolvedRadius.card,
              controlHeight,
              controlHeightSM,
              boxShadowTertiary: t.shadowSm,
            },
            components: {
              Layout: {
                siderBg: resolvedSidebar.bg,
                headerBg: resolvedSurface.surface,
                bodyBg: resolvedSurface.bg,
                headerHeight: shapeTokens.topbarHeight,
                headerPadding: '0 28px',
              },
              Menu: {
                darkItemBg: resolvedSidebar.bg,
                darkSubMenuItemBg: resolvedSidebar.bg,
                darkItemColor: resolvedSidebar.text,
                darkItemHoverBg: resolvedSidebar.hoverBg,
                darkItemHoverColor: resolvedSidebar.hoverText,
                darkItemSelectedBg: resolvedAccent.primary,
                darkItemSelectedColor: resolvedAccent.onAccent,
                darkGroupTitleColor: resolvedSidebar.mute,
                itemHeight: 38,
                itemBorderRadius: resolvedRadius.control,
                itemMarginBlock: 1,
                itemMarginInline: 0,
                itemPaddingInline: 12,
                iconSize: 18,
                collapsedIconSize: 18,
                iconMarginInlineEnd: 12,
                groupTitleFontSize: 10.5,
                groupTitleLineHeight: 1.45,
                fontSize: resolvedFontSize,
                activeBarBorderWidth: 0,
              },
              Button: {
                fontWeight: 600,
                primaryShadow: `0 6px 16px ${resolvedAccent.glow}`,
                defaultShadow: t.shadowSm,
                textTextColor: t.colorTextSecondary,
                paddingInline: 16,
                paddingInlineSM: 12,
                contentFontSizeSM: Math.max(12, resolvedFontSize - 1),
              },
              Segmented: {
                trackBg: resolvedSurface.surface,
                trackPadding: 3,
                itemColor: t.colorTextSecondary,
                itemHoverColor: t.colorText,
                itemHoverBg: 'transparent',
                itemSelectedBg: t.colorText,
                itemSelectedColor: resolvedSurface.surface,
                borderRadius: resolvedRadius.control,
                borderRadiusSM: Math.max(4, resolvedRadius.sm - 1),
                controlHeight,
                fontSize: Math.max(12, resolvedFontSize - 1),
              },
              Card: {
                borderRadiusLG: resolvedRadius.card,
                bodyPadding: 20,
              },
              Modal: { borderRadiusLG: resolvedRadius.modal },
              Badge: { dotSize: 8 },
            },
          }}
          tooltip={{
            styles: {
              container: {
                minHeight: 'unset',
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                padding: '5px 9px',
                fontSize: 13,
                lineHeight: 1.25,
              },
            },
          }}
          form={{
            requiredMark: (label, { required }) => (
              <>
                {label}
                {required ? (
                  <span aria-hidden="true" style={{ marginLeft: 3, color: t.colorError }}>
                    *
                  </span>
                ) : null}
              </>
            ),
          }}
        >
          <AntdApp>{children}</AntdApp>
        </ConfigProvider>
      </AntdRegistry>
    </ThemeContext.Provider>
  );
}
