import { useEffect } from "react";
import { useSelector } from "react-redux";
import { RootState } from "@/store/store";
import { getHeader } from "../services/api/header";

// Oliver default brand colors
const DEFAULT_PRIMARY = "#5146E5";
const DEFAULT_SECONDARY = "#E9E8F8";
const DEFAULT_ACCENT = "#3D35B0";

interface BrandColors {
  primary: string;
  secondary: string;
  accent: string;
}

function hexToHSL(hex: string): string {
  hex = hex.replace("#", "");
  const r = parseInt(hex.substring(0, 2), 16) / 255;
  const g = parseInt(hex.substring(2, 4), 16) / 255;
  const b = parseInt(hex.substring(4, 6), 16) / 255;

  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  const l = (max + min) / 2;

  if (max === min) return `0 0% ${Math.round(l * 100)}%`;

  const d = max - min;
  const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  let h = 0;
  if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
  else if (max === g) h = ((b - r) / d + 2) / 6;
  else h = ((r - g) / d + 4) / 6;

  return `${Math.round(h * 360)} ${Math.round(s * 100)}% ${Math.round(l * 100)}%`;
}

function lighten(hex: string, amount: number): string {
  hex = hex.replace("#", "");
  let r = parseInt(hex.substring(0, 2), 16);
  let g = parseInt(hex.substring(2, 4), 16);
  let b = parseInt(hex.substring(4, 6), 16);
  r = Math.min(255, Math.round(r + (255 - r) * amount));
  g = Math.min(255, Math.round(g + (255 - g) * amount));
  b = Math.min(255, Math.round(b + (255 - b) * amount));
  return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
}

function darken(hex: string, amount: number): string {
  hex = hex.replace("#", "");
  let r = parseInt(hex.substring(0, 2), 16);
  let g = parseInt(hex.substring(2, 4), 16);
  let b = parseInt(hex.substring(4, 6), 16);
  r = Math.max(0, Math.round(r * (1 - amount)));
  g = Math.max(0, Math.round(g * (1 - amount)));
  b = Math.max(0, Math.round(b * (1 - amount)));
  return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
}

/**
 * Hook that sets CSS custom properties based on the selected client's brand config.
 * Falls back to Oliver default colors when no client is selected.
 */
export function useBrandTheme() {
  const selectedClientId = useSelector(
    (s: RootState) => s.client.selectedClientId
  );

  useEffect(() => {
    if (!selectedClientId) {
      applyColors({ primary: DEFAULT_PRIMARY, secondary: DEFAULT_SECONDARY, accent: DEFAULT_ACCENT });
      return;
    }

    // Fetch brand config for selected client
    fetch(`/api/v1/admin/clients/${selectedClientId}/brand`, {
      headers: getHeader(),
    })
      .then((res) => {
        if (!res.ok) throw new Error("No brand config");
        return res.json();
      })
      .then((brand) => {
        const primary =
          brand.primary_colors?.[0] ? `#${brand.primary_colors[0].replace("#", "")}` : DEFAULT_PRIMARY;
        const secondary = lighten(primary, 0.85);
        const accent = darken(primary, 0.2);
        applyColors({ primary, secondary, accent });
      })
      .catch(() => {
        applyColors({ primary: DEFAULT_PRIMARY, secondary: DEFAULT_SECONDARY, accent: DEFAULT_ACCENT });
      });
  }, [selectedClientId]);
}

function applyColors(colors: BrandColors) {
  const root = document.documentElement;
  root.style.setProperty("--brand-primary", colors.primary);
  root.style.setProperty("--brand-secondary", colors.secondary);
  root.style.setProperty("--brand-accent", colors.accent);
}
