"use client";

import { useState, useCallback, useMemo } from "react";
import type { XmlGeneratorConfig, XmlGeneratorMode } from "../types";
import { DEFAULT_PRESETS } from "../services/category-presets";

function createDefaultConfig(): XmlGeneratorConfig {
  const categories: Record<string, { name: string; fieldsText: string }> = {};
  for (const [name, fields] of Object.entries(DEFAULT_PRESETS)) {
    categories[name] = { name, fieldsText: fields.join("\n") };
  }
  return {
    baseNamespace: "http://schemas.beletage.ro/contract",
    mode: "advanced",
    categories,
    currentCategory: "Beneficiar",
  };
}

export function useXmlConfig() {
  const [config, setConfig] = useState<XmlGeneratorConfig>(createDefaultConfig);

  const setMode = useCallback((mode: XmlGeneratorMode) => {
    setConfig((prev) => ({ ...prev, mode }));
  }, []);

  const setBaseNamespace = useCallback((baseNamespace: string) => {
    setConfig((prev) => ({ ...prev, baseNamespace }));
  }, []);

  const setCurrentCategory = useCallback((name: string) => {
    setConfig((prev) => ({ ...prev, currentCategory: name }));
  }, []);

  const updateCategoryFields = useCallback(
    (categoryName: string, fieldsText: string) => {
      setConfig((prev) => {
        const existing = prev.categories[categoryName];
        if (!existing) return prev;
        return {
          ...prev,
          categories: {
            ...prev.categories,
            [categoryName]: { name: existing.name, fieldsText },
          },
        };
      });
    },
    [],
  );

  const addCategory = useCallback((name: string) => {
    setConfig((prev) => {
      if (prev.categories[name]) return prev;
      return {
        ...prev,
        categories: { ...prev.categories, [name]: { name, fieldsText: "" } },
        currentCategory: name,
      };
    });
  }, []);

  const removeCategory = useCallback((name: string) => {
    setConfig((prev) => {
      const next = { ...prev.categories };
      delete next[name];
      const keys = Object.keys(next);
      return {
        ...prev,
        categories: next,
        currentCategory: keys.includes(prev.currentCategory)
          ? prev.currentCategory
          : keys[0] || "",
      };
    });
  }, []);

  const resetCategoryToPreset = useCallback((name: string) => {
    const preset = DEFAULT_PRESETS[name];
    if (!preset) return;
    setConfig((prev) => ({
      ...prev,
      categories: {
        ...prev.categories,
        [name]: { name, fieldsText: preset.join("\n") },
      },
    }));
  }, []);

  const clearCategoryFields = useCallback((name: string) => {
    setConfig((prev) => {
      const existing = prev.categories[name];
      if (!existing) return prev;
      return {
        ...prev,
        categories: {
          ...prev.categories,
          [name]: { name: existing.name, fieldsText: "" },
        },
      };
    });
  }, []);

  const resetAll = useCallback(() => {
    setConfig(createDefaultConfig());
  }, []);

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

  return useMemo(
    () => ({
      config,
      setMode,
      setBaseNamespace,
      setCurrentCategory,
      updateCategoryFields,
      addCategory,
      removeCategory,
      resetCategoryToPreset,
      clearCategoryFields,
      resetAll,
      loadConfig,
    }),
    [
      config,
      setMode,
      setBaseNamespace,
      setCurrentCategory,
      updateCategoryFields,
      addCategory,
      removeCategory,
      resetCategoryToPreset,
      clearCategoryFields,
      resetAll,
      loadConfig,
    ],
  );
}
