'use client';

import { useEffect, useRef } from 'react';
import {
  getThemeById,
  type DesignTheme,
  type ThemeColors,
} from '@/lib/themes';

const STORAGE_KEY = 'fitcrm-theme';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/v1';
const POLL_INTERVAL = 30_000;

function applyTheme(theme: DesignTheme) {
  const root = document.documentElement;

  for (const [key, value] of Object.entries(theme.colors) as [keyof ThemeColors, string][]) {
    root.style.setProperty(key, value);
    const tailwindKey = `--color-${key.slice(2)}`;
    root.style.setProperty(tailwindKey, value);
  }

  root.style.setProperty('--font-heading', theme.fonts.heading);
  root.style.setProperty('--font-body', theme.fonts.body);
  document.body.style.fontFamily = `${theme.fonts.body}, system-ui, -apple-system, sans-serif`;

  if (theme.fonts.importUrl) {
    const existingLink = document.getElementById('theme-font-link');
    if (existingLink) existingLink.remove();

    const link = document.createElement('link');
    link.id = 'theme-font-link';
    link.rel = 'stylesheet';
    link.href = theme.fonts.importUrl;
    document.head.appendChild(link);
  }

  root.dataset.theme = theme.id;
  root.dataset.dark = theme.isDark ? 'true' : 'false';
}

async function fetchActiveTheme(): Promise<string | null> {
  try {
    const res = await fetch(`${API_BASE}/theme/current`, { cache: 'no-store' });
    if (!res.ok) return null;
    const data = await res.json() as { themeId?: string };
    return data.themeId ?? null;
  } catch {
    return null;
  }
}

let currentThemeId: string | null = null;

function syncAndApply(themeId: string) {
  if (themeId === currentThemeId) return;
  const theme = getThemeById(themeId);
  if (!theme) return;
  currentThemeId = themeId;
  applyTheme(theme);
  localStorage.setItem(STORAGE_KEY, themeId);
}

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);

  useEffect(() => {
    // 1. Instant: localStorage cache for fast paint
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored && getThemeById(stored)) {
      syncAndApply(stored);
    }

    // 2. Fetch from API (source of truth)
    const syncFromApi = () => {
      void fetchActiveTheme().then((apiThemeId) => {
        if (apiThemeId) syncAndApply(apiThemeId);
      });
    };

    syncFromApi();

    // 3. Poll every 30s for cross-app theme changes
    pollRef.current = setInterval(syncFromApi, POLL_INTERVAL);

    return () => {
      if (pollRef.current) clearInterval(pollRef.current);
    };
  }, []);

  return <>{children}</>;
}
