import axios from "axios";
import {
  TemplateSettingValue,
  TemplateSettingValueResponse,
  CreateTemplateSettingValuePayload,
} from "../types/templateSettingValueTypes";
import Cookies from "js-cookie";
import { getEnvUrl } from "@/shared/config/env";

const TENANT_ID = "adf98293-41ba-4bda-bdb4-70e30a70c1b7";
const API_URL = getEnvUrl("VITE_RECORD_API_URL", false);

const apiInstance = axios.create({
  baseURL: API_URL,
});

apiInstance.interceptors.request.use((config) => {
  const token = Cookies.get("auth-token");
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  config.headers["x-tenant-id"] = TENANT_ID;
  return config;
});

export const TemplateSettingValueService = {
  async getTemplateSettingValues(
    templateSettingId: string,
    params?: Record<string, unknown>,
  ): Promise<TemplateSettingValueResponse> {
    try {
      const response = await apiInstance.get(
        `/template-setting-values/list/${templateSettingId}`,
        {
          params,
        },
      );
      console.log("getTemplateSettingValues response:", response.data);
      // Ensure we return the correct structure
      if (response.data && typeof response.data === "object") {
        if (Array.isArray(response.data)) {
          return {
            count: response.data.length,
            items: response.data
              .filter(
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                (item: any) => item && typeof item === "object" && "id" in item,
              )
              .map(
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                (item: any) => ({
                  ...item,
                  name:
                    typeof item.name === "object"
                      ? item.name?.en || item.name?.am || ""
                      : item.name || "",
                  value:
                    typeof item.value === "object"
                      ? item.value?.en || item.value?.am || ""
                      : item.value || "",
                  templateName:
                    typeof item.template?.name === "object"
                      ? item.template?.name?.en || item.template?.name?.am || ""
                      : item.template?.name || "",
                  templateSettingName:
                    typeof item.templateSetting?.name === "object"
                      ? item.templateSetting?.name?.en ||
                        item.templateSetting?.name?.am ||
                        ""
                      : item.templateSetting?.name || "",
                }),
              ),
          };
        }
        if ("items" in response.data && Array.isArray(response.data.items)) {
          return {
            count: response.data.count || response.data.items.length,
            items: response.data.items
              .filter(
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                (item: any) => item && typeof item === "object" && "id" in item,
              )
              .map(
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                (item: any) => ({
                  ...item,
                  name:
                    typeof item.name === "object"
                      ? item.name?.en || item.name?.am || ""
                      : item.name || "",
                  value:
                    typeof item.value === "object"
                      ? item.value?.en || item.value?.am || ""
                      : item.value || "",
                  templateName:
                    typeof item.template?.name === "object"
                      ? item.template?.name?.en || item.template?.name?.am || ""
                      : item.template?.name || "",
                  templateSettingName:
                    typeof item.templateSetting?.name === "object"
                      ? item.templateSetting?.name?.en ||
                        item.templateSetting?.name?.am ||
                        ""
                      : item.templateSetting?.name || "",
                }),
              ),
          };
        }
      }
      return {
        count: 0,
        items: [],
      };
    } catch (error) {
      console.error("getTemplateSettingValues error:", error);
      // If endpoint doesn't exist, return empty list
      return {
        count: 0,
        items: [],
      };
    }
  },
  async getTemplateSettingValue(id: string): Promise<TemplateSettingValue> {
    const response = await apiInstance.get(`/template-setting-values/${id}`);
    return response.data;
  },

  async createTemplateSettingValue(
    data: CreateTemplateSettingValuePayload,
  ): Promise<TemplateSettingValue> {
    const response = await apiInstance.post("/template-setting-values", data);
    return response.data;
  },

  async updateTemplateSettingValue(
    id: string,
    data: Partial<CreateTemplateSettingValuePayload>,
  ): Promise<TemplateSettingValue> {
    const response = await apiInstance.put(
      `/template-setting-values/${id}`,
      data,
    );
    return response.data;
  },

  async deleteTemplateSettingValue(id: string): Promise<void> {
    await apiInstance.delete(`/template-setting-values/${id}`);
  },

  async getTemplates(): Promise<Record<string, unknown>> {
    const response = await apiInstance.get("/templates");
    const data = response.data;
    console.log("getTemplates response:", data);
    // Handle both array and object responses
    if (Array.isArray(data)) {
      return { items: data };
    }
    if (data && typeof data === "object" && "items" in data) {
      return data;
    }
    return { items: [] };
  },

  async getTemplateSettings(
    templateId: string,
  ): Promise<Record<string, unknown>> {
    const response = await apiInstance.get(
      `/template-settings/list/${templateId}`,
    );
    const data = response.data;
    console.log("getTemplateSettings response:", data);
    // Handle both array and object responses
    if (Array.isArray(data)) {
      return { items: data };
    }
    if (data && typeof data === "object" && "items" in data) {
      return data;
    }
    return { items: [] };
  },

  async getResources(resourceTypeId: string): Promise<Record<string, unknown>> {
    const response = await apiInstance.get(`/resources/list/${resourceTypeId}`);
    const data = response.data;
    console.log("getResources response:", data);
    // Handle both array and object responses
    if (Array.isArray(data)) {
      return { items: data };
    }
    if (data && typeof data === "object" && "items" in data) {
      return data;
    }
    return { items: [] };
  },

  async getResourceTypes(): Promise<Record<string, unknown>> {
    const response = await apiInstance.get("/resource_types");
    const data = response.data;
    console.log("getResourceTypes response:", data);
    // Handle both array and object responses
    if (Array.isArray(data)) {
      return { items: data };
    }
    if (data && typeof data === "object" && "items" in data) {
      return data;
    }
    return { items: [] };
  },
};
