"use client";

import { useState, useCallback, useMemo } from "react";
import type { CompanyId } from "@/core/auth/types";
import type {
  SignatureConfig,
  SignatureVariant,
  SignatureColors,
  SignatureLayout,
} from "../types";
import { getBranding } from "../services/company-branding";

const DEFAULT_LAYOUT: SignatureLayout = {
  greenLineWidth: 97,
  gutterWidth: 13,
  iconTextSpacing: 5,
  iconVerticalOffset: 1,
  mottoSpacing: 3,
  sectionSpacing: 10,
  titleSpacing: 2,
  logoSpacing: 10,
  logoScale: 1,
};

function createDefaultConfig(company: CompanyId = "beletage"): SignatureConfig {
  const branding = getBranding(company);
  return {
    prefix: "arh.",
    name: "",
    title: "",
    phone: "",
    company,
    colors: { ...branding.defaultColors },
    layout: { ...DEFAULT_LAYOUT },
    variant: "full",
    useSvg: false,
  };
}

export function useSignatureConfig(initialCompany: CompanyId = "beletage") {
  const [config, setConfig] = useState<SignatureConfig>(() =>
    createDefaultConfig(initialCompany),
  );

  const updateField = useCallback(
    <K extends keyof SignatureConfig>(key: K, value: SignatureConfig[K]) => {
      setConfig((prev) => ({ ...prev, [key]: value }));
    },
    [],
  );

  const updateColor = useCallback(
    (key: keyof SignatureColors, value: string) => {
      setConfig((prev) => ({
        ...prev,
        colors: { ...prev.colors, [key]: value },
      }));
    },
    [],
  );

  const updateLayout = useCallback(
    (key: keyof SignatureLayout, value: number) => {
      setConfig((prev) => ({
        ...prev,
        layout: { ...prev.layout, [key]: value },
      }));
    },
    [],
  );

  const setVariant = useCallback((variant: SignatureVariant) => {
    setConfig((prev) => ({ ...prev, variant }));
  }, []);

  const setCompany = useCallback((company: CompanyId) => {
    const branding = getBranding(company);
    setConfig((prev) => ({
      ...prev,
      company,
      colors: { ...branding.defaultColors },
    }));
  }, []);

  const setAddress = useCallback((address: string[]) => {
    setConfig((prev) => ({ ...prev, addressOverride: address }));
  }, []);

  const resetToDefaults = useCallback(() => {
    setConfig(createDefaultConfig(config.company));
  }, [config.company]);

  const loadConfig = useCallback((loaded: SignatureConfig) => {
    setConfig(loaded);
  }, []);

  return useMemo(
    () => ({
      config,
      updateField,
      updateColor,
      updateLayout,
      setVariant,
      setCompany,
      setAddress,
      resetToDefaults,
      loadConfig,
    }),
    [
      config,
      updateField,
      updateColor,
      updateLayout,
      setVariant,
      setCompany,
      setAddress,
      resetToDefaults,
      loadConfig,
    ],
  );
}
