import { computed } from 'vue';
import { useState, useRequestHeaders, useHead, useRuntimeConfig } from '#imports';
import { getApiBaseUrl } from '../utils/api';
import { resolveMediaUrl } from './useProducts';
import { resolveTheme, FONT_FALLBACK } from './useThemeVars';

interface ColorScheme {
  primary?: string;
  secondary?: string;
  accent?: string;
  bodyColor?: string;
}

interface Fonts {
  headingFont?: string;
  bodyFont?: string;
  headingWeight?: string;
  bodyWeight?: string;
}

interface ContactInfo {
  phone?: string;
  email?: string;
  address?: string;
  socialMedia?: {
    facebook?: string;
    instagram?: string;
    twitter?: string;
  };
}

interface SiteConfig {
  id: string;
  organizationId: string;
  publicApiToken: string; // Token for public store API access
  siteName?: string;
  siteDescription?: string;
  logoUrl?: string;
  faviconUrl?: string;
  heroImageUrl?: string;
  contactInfo?: ContactInfo;
  subdomain?: string;
  customDomain?: string;
  isPublished: boolean;
  template: {
    code: string;
    name: string;
    type: string;
  };
  customization?: {
    colors?: ColorScheme;
    fonts?: Fonts;
    customCSS?: string;
    componentSettings?: any;
    content?: any;
    values?: any; // Dynamic settings values
  };
}

export const useSiteConfig = () => {
  // useState — SSR-safe, дані передаються клієнту через гідрацію
  const siteConfig = useState<SiteConfig | null>('site-config', () => null);
  const loading = useState<boolean>('site-config-loading', () => false);
  const error = useState<string | null>('site-config-error', () => null);

  // Отримати subdomain з host — працює і на SSR, і на клієнті
  const getSubdomain = () => {
    let hostname = '';

    if (import.meta.server) {
      // Фіксований магазин екземпляра (деплой «один контейнер — один клієнт»): STORE_SUBDOMAIN має пріоритет над хостом
      const fixed = String((useRuntimeConfig() as any).storeSubdomain || '').trim();
      if (fixed) return fixed;
      // SSR: за роутером платформи (nginx → template_router → шаблон) піддомен приходить у X-Subdomain,
      // а Host уже переписаний на ім'я контейнера; інакше — з host / x-forwarded-host
      const headers = useRequestHeaders(['host', 'x-forwarded-host', 'x-subdomain']);
      const fromRouter = String(headers['x-subdomain'] || '').trim().toLowerCase();
      if (fromRouter) return fromRouter;
      hostname = (headers['x-forwarded-host'] || headers['host'] || '').split(':')[0];
    } else {
      // Client: з window.location
      hostname = window.location.hostname;
    }

    const parts = hostname.split('.');
    // Локальна розробка: shop.localhost → "shop"
    if (parts.length === 2 && parts[1] === 'localhost') {
      return parts[0];
    }
    // Формат: subdomain.domain.com або subdomain.domain.com.ua
    if (parts.length >= 3) {
      return parts[0];
    }
    return null;
  };

  // Fetch site configuration from API
  const fetchConfig = async (subdomain?: string) => {
    // Якщо вже завантажено — не перезавантажуємо
    if (siteConfig.value && !subdomain) return siteConfig.value;

    loading.value = true;
    error.value = null;

    try {
      const sub = subdomain || getSubdomain();
      if (!sub) {
        throw new Error('Subdomain not found');
      }

      const response = await $fetch<SiteConfig>(
        `/site-template/public/config/subdomain/${sub}`,
        {
          baseURL: getApiBaseUrl(),
        }
      );

      siteConfig.value = response;
      applyCustomization();
      updateMetaTags();
      return response;
    } catch (e: any) {
      error.value = e.message || 'Failed to load site configuration';
      console.error('Error loading site config:', e);
      throw e;
    } finally {
      loading.value = false;
    }
  };

  // Apply color customization as CSS variables
  const applyCustomization = () => {
    if (!siteConfig.value?.customization) return;

    const { customCSS } = siteConfig.value.customization;
    // Кольори/шрифти: values.colors/values.fonts («Налаштування шаблону») мають пріоритет над старими полями
    const theme = resolveTheme(siteConfig.value.customization);
    const colors = {
      primary: theme.colors.primary,
      secondary: theme.colors.secondary,
      accent: theme.colors.accent,
      bodyColor: theme.colors.body,
    };
    const fonts = {
      ...(siteConfig.value.customization.fonts || {}),
      // Той самий стек, що й у useThemeVars (з фолбеком для кирилиці)
      headingFont: theme.fonts.heading ? `'${theme.fonts.heading}', ${FONT_FALLBACK}` : '',
      bodyFont: theme.fonts.body ? `'${theme.fonts.body}', ${FONT_FALLBACK}` : '',
    };

    if (import.meta.client && colors) {
      const root = document.documentElement;

      if (colors.primary) {
        root.style.setProperty('--primary-color', colors.primary);
        root.style.setProperty('--bs-primary', colors.primary);
      }
      if (colors.secondary) {
        root.style.setProperty('--secondary-color', colors.secondary);
        root.style.setProperty('--bs-secondary', colors.secondary);
      }
      if (colors.accent) {
        root.style.setProperty('--accent-color', colors.accent);
      }
      if (colors.bodyColor) {
        root.style.setProperty('--body-color', colors.bodyColor);
      }
    }

    if (import.meta.client && fonts) {
      const root = document.documentElement;

      if (fonts.headingFont) {
        root.style.setProperty('--font-family-heading', fonts.headingFont);
      }
      if (fonts.bodyFont) {
        root.style.setProperty('--font-family-body', fonts.bodyFont);
      }
      if (fonts.headingWeight) {
        root.style.setProperty('--font-weight-heading', fonts.headingWeight);
      }
      if (fonts.bodyWeight) {
        root.style.setProperty('--font-weight-body', fonts.bodyWeight);
      }
    }

    // Inject custom CSS
    if (import.meta.client && customCSS) {
      let styleEl = document.getElementById('custom-site-css');
      if (!styleEl) {
        styleEl = document.createElement('style');
        styleEl.id = 'custom-site-css';
        document.head.appendChild(styleEl);
      }
      styleEl.textContent = customCSS;
    }
  };

  // SEO: мета-теги з налаштувань сайту (SSR-сумісно через useHead)
  const updateMetaTags = () => {
    if (!siteConfig.value) return;

    const { siteName, siteDescription, logoUrl, faviconUrl } = siteConfig.value;
    // SEO приходить верхнім полем конфігу (seo), старіші конфіги тримали його в customization.content.seo
    const seo = (siteConfig.value as any).seo || siteConfig.value.customization?.content?.seo || {};

    const title = seo.metaTitle || siteName;
    const description = seo.metaDescription || siteDescription;
    const ogImage = resolveMediaUrl(seo.ogImage || logoUrl);

    const meta: Array<Record<string, string>> = [];
    const add = (key: 'name' | 'property', id: string, content?: string) => {
      if (content) meta.push({ [key]: id, content });
    };
    add('name', 'description', description);
    add('name', 'keywords', seo.metaKeywords);
    add('property', 'og:title', seo.ogTitle || title);
    add('property', 'og:description', seo.ogDescription || description);
    add('property', 'og:image', ogImage);
    add('property', 'og:site_name', siteName);

    useHead({
      ...(title ? { title } : {}),
      meta,
      // favicon може бути відносним шляхом медіа-сервера — доповнюємо mediaBase
      link: faviconUrl ? [{ rel: 'icon', href: resolveMediaUrl(faviconUrl) }] : [],
    });
  };

  // Computed properties
  const organizationId = computed(() => siteConfig.value?.organizationId);
  const publicApiToken = computed(() => siteConfig.value?.publicApiToken);
  const siteName = computed(() => siteConfig.value?.siteName);
  const logoUrl = computed(() => siteConfig.value?.logoUrl);
  const contactInfo = computed(() => siteConfig.value?.contactInfo);
  const isPublished = computed(() => siteConfig.value?.isPublished);
  const componentSettings = computed(() => siteConfig.value?.customization?.componentSettings || {});
  const settingsValues = computed(() => siteConfig.value?.customization?.values || {});

  return {
    siteConfig,
    loading,
    error,
    fetchConfig,
    applyCustomization,
    updateMetaTags,
    organizationId,
    publicApiToken,
    siteName,
    logoUrl,
    contactInfo,
    isPublished,
    componentSettings,
    settingsValues,
  };
};
