import { useEffect, useState } from "react";
import { TemplateService } from "@/user-management/services/api/templateService";
import { TemplateSampleSetting, TemplateResource } from "@/user-management/services/TemplateConfiguration/types/templateTypes";

export const useTemplateSettings = (templateId: string, unitId?: string) => {
  const [settings, setSettings] = useState<TemplateSampleSetting[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!templateId) return;

    const fetchSettings = async () => {
      try {
        setLoading(true);
        setError(null);

        // First, get all templates to find the one with matching ID
        const allTemplatesResponse = await TemplateService.getAllTemplates();
        const template = allTemplatesResponse.items?.find(
          (t: TemplateResource) => t.id === templateId,
        );

        if (!template) {
          throw new Error("Template not found");
        }

        // Then fetch settings using the template ID
        const fetchedSettings = await TemplateService.getTemplateSettingsByUnit(
          template.id,
          unitId,
        );
        setSettings(fetchedSettings.items && fetchedSettings.items.length > 0 ? fetchedSettings.items : getDefaultSettings());
      } catch (err) {
        console.error("Error loading template settings:", err);
        setError("Failed to load template settings");
        // Fall back to default settings
        setSettings(getDefaultSettings());
      } finally {
        setLoading(false);
      }
    };

    fetchSettings();
  }, [templateId, unitId]);

  return {
    settings,
    loading,
    error,
    setSettings,
  };
};

// Default settings fallback
export const getDefaultSettings = (): TemplateSampleSetting[] => [
  {
    id: "default-subject-style",
    code: "subject-style",
    value: {
      "font-size": "60px",
      "font-weight": "bold",
      "text-decoration": "",
    },
  },
  {
    id: "default-body-style",
    code: "body-style",
    value: {
      "font-size": "14px",
      "font-weight": "normal",
      "text-decoration": "",
    },
  },
];
