import { useEffect, useState } from "react";
import { createClient } from "@metagptx/web-sdk";

const client = createClient();

export type BrandSlide = { id: string; title: string; subtitle: string; cta: string; ctaLink: string };
export type BrandState = {
  logoUrl: string;
  faviconUrl: string;
  primary: string;
  secondary: string;
  accent: string;
  bg: string;
  fontHeading: string;
  fontBody: string;
  headingScale: number;
  slides: BrandSlide[];
};

export const BRAND_DEFAULTS: BrandState = {
  logoUrl: "/logo.svg",
  faviconUrl: "/logo.svg",
  primary: "#0b6e3e",
  secondary: "#063019",
  accent: "#f5c400",
  bg: "#03120a",
  fontHeading: "Inter",
  fontBody: "Inter",
  headingScale: 100,
  slides: [],
};

export type LoginLayout = "classic" | "split" | "minimal" | "glass";

export type LoginBranding = {
  layout: LoginLayout;
  welcomeTitle: string;
  welcomeSubtitle: string;
  backgroundUrl: string;
  backgroundVideoUrl: string;
  showSocialLogin: boolean;
  showRememberMe: boolean;
  showForgotPassword: boolean;
  ctaLabel: string;
};

export const LOGIN_DEFAULTS: LoginBranding = {
  layout: "split",
  welcomeTitle: "Welcome back to DoItEasy",
  welcomeSubtitle: "Manage hosting, VPS, domains and tickets from one premium dashboard.",
  backgroundUrl: "/assets/images/image-1.png",
  backgroundVideoUrl: "/assets/hero-servers-data.mp4",
  showSocialLogin: false,
  showRememberMe: true,
  showForgotPassword: true,
  ctaLabel: "Sign In",
};

/**
 * Read a site_settings row from the backend, fall back to localStorage
 * mirror, and finally the provided defaults. A compact helper used by
 * the `useBranding`, `useLoginBranding`, `useRegistrationConfig` hooks
 * below so every page of the site can reflect admin changes live.
 */
function readLSMirror<T>(key: string, fallback: T): T {
  try {
    // New unified key written by useSiteSettings
    const raw = localStorage.getItem(`site_settings:${key}`);
    if (raw) return { ...fallback, ...JSON.parse(raw) };
  } catch {
    /* ignore */
  }
  try {
    // Legacy key for backward compatibility
    const raw = localStorage.getItem(`cms:${key}`);
    if (raw) return { ...fallback, ...JSON.parse(raw) };
  } catch {
    /* ignore */
  }
  return fallback;
}

async function fetchSiteSettings<T>(key: string, fallback: T): Promise<T> {
  try {
    const resp: any = await (client.entities as any).site_settings.queryAll({
      query: { key },
      limit: 1,
    });
    const items = resp?.data?.items ?? [];
    if (items.length > 0) {
      const parsed = JSON.parse(items[0].value_json ?? "{}");
      localStorage.setItem(`site_settings:${key}`, JSON.stringify(parsed));
      return { ...fallback, ...parsed };
    }
  } catch {
    /* ignore */
  }
  return fallback;
}

function useBackedSettings<T>(key: string, fallback: T): T {
  const [state, setState] = useState<T>(() => readLSMirror(key, fallback));
  useEffect(() => {
    let alive = true;
    fetchSiteSettings<T>(key, fallback).then((v) => {
      if (alive && v !== fallback) setState(v);
    });
    const onStorage = () => setState(readLSMirror(key, fallback));
    const onUpdate = (ev: Event) => {
      const ce = ev as CustomEvent;
      if (!ce?.detail || ce.detail.key === key) {
        fetchSiteSettings<T>(key, fallback).then((v) => {
          if (alive) setState(v);
        });
      }
    };
    window.addEventListener("storage", onStorage);
    window.addEventListener("site_settings:updated", onUpdate as EventListener);
    return () => {
      alive = false;
      window.removeEventListener("storage", onStorage);
      window.removeEventListener("site_settings:updated", onUpdate as EventListener);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [key]);
  return state;
}

export function useBranding(): BrandState {
  return useBackedSettings<BrandState>("branding", BRAND_DEFAULTS);
}

export function useLoginBranding(): LoginBranding {
  return useBackedSettings<LoginBranding>("login_page", LOGIN_DEFAULTS);
}

export type RegistrationConfig = {
  open: boolean;
  requireEmailVerify: boolean;
  requireCaptcha: boolean;
  requirePhone: boolean;
  requireCompany: boolean;
  requireCountry: boolean;
  requirePlanSelection: boolean;
  defaultRole: "client" | "support" | "billing";
  approval: "auto" | "manual";
  allowedDomains: string[];
  blockedDomains: string[];
  termsUrl: string;
  welcomeMessage: string;
};

export const REGISTRATION_DEFAULTS: RegistrationConfig = {
  open: true,
  requireEmailVerify: true,
  requireCaptcha: true,
  requirePhone: true,
  requireCompany: false,
  requireCountry: true,
  requirePlanSelection: true,
  defaultRole: "client",
  approval: "auto",
  allowedDomains: [],
  blockedDomains: [],
  termsUrl: "/service-terms",
  welcomeMessage: "Welcome to DoItEasy — your account is ready.",
};

export function useRegistrationConfig(): RegistrationConfig {
  return useBackedSettings<RegistrationConfig>("registration", REGISTRATION_DEFAULTS);
}

export type PendingRegistration = {
  id: string;
  name: string;
  email: string;
  company: string;
  country: string;
  plan: string;
  status: "pending" | "approved" | "rejected";
  submittedAt: string;
};

export const DEFAULT_PENDING: PendingRegistration[] = [
  { id: "r1", name: "Layla Saeed", email: "layla@acme.sa", company: "ACME Logistics", country: "Saudi Arabia", plan: "Business VDS", status: "pending", submittedAt: "10 min ago" },
  { id: "r2", name: "Hassan Tariq", email: "hassan@fincorp.kw", company: "FinCorp KW", country: "Kuwait", plan: "Enterprise Dedicated", status: "pending", submittedAt: "2 h ago" },
  { id: "r3", name: "Noura Farouk", email: "noura@gulfmed.eg", company: "GulfMed", country: "Egypt", plan: "Starter VPS", status: "approved", submittedAt: "Yesterday" },
  { id: "r4", name: "Yousef Al-Jabri", email: "yousef@startupx.io", company: "StartupX", country: "UAE", plan: "Business VDS", status: "rejected", submittedAt: "2 days ago" },
];