import axios, { AxiosResponse } from "axios";
import Cookies from "js-cookie";
import { getEnvUrl } from "@/shared/config/env";

export interface MetabaseDashboard {
  id: string;
  name: {
    am: string;
    en: string;
  };
  description: {
    am: string;
    en: string;
  };
  metabaseDashboardNumber: number;
  permissionId: string;
  createdAt: string;
  updatedAt: string;
  tenantId: string;
  params: string[];
}

export interface MetabaseDashboardsResponse {
  count: number;
  items: MetabaseDashboard[];
}

export interface MetabaseIframeResponse {
  iframeUrl: string;
}

export interface CreateDashboardRequest {
  name: {
    am: string;
    en: string;
  };
  metabaseDashboardNumber: number;
  description: {
    am: string;
    en: string;
  };
  permissionId: string;
  params: Record<string, unknown>[];
}

export interface GetIframeUrlRequest {
  params: Record<string, unknown>;
}

// Create a dedicated axios instance for Metabase API
const metabaseAxios = axios.create({
  baseURL: getEnvUrl("VITE_CHRONICLE_URL", false),
});

// Add auth token interceptor
metabaseAxios.interceptors.request.use((config) => {
  const token = Cookies.get("auth-token");
  if (token) {
    config.headers["Authorization"] = `Bearer ${token}`;
  }
  // Add tenant ID header
  config.headers["x-tenant-id"] = "adf98293-41ba-4bda-bdb4-70e30a70c1b7";
  return config;
});

class MetabaseService {
  private baseUrl = "/metabase-dashboards";

  async createDashboard(
    data: CreateDashboardRequest,
  ): Promise<MetabaseDashboard> {
    const response: AxiosResponse<MetabaseDashboard> = await metabaseAxios.post(
      this.baseUrl,
      data,
    );
    return response.data;
  }

  async getAllDashboards(): Promise<MetabaseDashboardsResponse> {
    const response: AxiosResponse<MetabaseDashboardsResponse> =
      await metabaseAxios.get(this.baseUrl);
    return response.data;
  }

  async getPermittedDashboards(
    locale: string = "en",
  ): Promise<MetabaseDashboardsResponse> {
    const response: AxiosResponse<MetabaseDashboardsResponse> =
      await metabaseAxios.get(`${this.baseUrl}/permitted`, {
        params: {
          locale,
        },
      });
    return response.data;
  }

  async getIframeUrl(
    dashboardId: string,
    params: GetIframeUrlRequest,
  ): Promise<MetabaseIframeResponse> {
    const response: AxiosResponse<MetabaseIframeResponse> =
      await metabaseAxios.post(
        `${this.baseUrl}/${dashboardId}/iframe-url`,
        params,
      );
    return response.data;
  }

  async getFilteredDashboardUrl(
    dashboardId: string,
    planYearId: string,
  ): Promise<MetabaseIframeResponse> {
    const params: GetIframeUrlRequest = {
      params: {
        plan_year: planYearId,
      },
    };

    const response: AxiosResponse<MetabaseIframeResponse> =
      await metabaseAxios.post(
        `${this.baseUrl}/${dashboardId}/iframe-url`,
        params,
      );
    return response.data;
  }
}

export const metabaseService = new MetabaseService();

// Helper function to create a performance dashboard
export const createPerformanceDashboard = async () => {
  const dashboardData: CreateDashboardRequest = {
    name: {
      am: "performance",
      en: "performance",
    },
    metabaseDashboardNumber: 2,
    description: {
      am: "performance",
      en: "performance",
    },
    permissionId: "a83825b9-9806-4918-bc10-56226bbe41d4",
    params: [],
  };

  return metabaseService.createDashboard(dashboardData);
};
