import { useState, useEffect, useRef, useCallback } from "react";
import { useTranslation } from "react-i18next";
import {
  metabaseService,
  MetabaseDashboard,
  GetIframeUrlRequest,
} from "../services/api/metabaseService";

export const useMetabaseDashboard = () => {
  const { i18n } = useTranslation();
  const [dashboards, setDashboards] = useState<MetabaseDashboard[]>([]);
  const [selectedDashboard, setSelectedDashboard] =
    useState<MetabaseDashboard | null>(null);
  const [iframeUrl, setIframeUrl] = useState<string>("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const currentRequestRef = useRef<string | null>(null);

  const fetchDashboards = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await metabaseService.getPermittedDashboards(
        i18n.language === "am" ? "am" : "en",
      );
      setDashboards(response.items);

      // Auto-select the first dashboard if available
      if (response.items.length > 0 && !selectedDashboard) {
        setSelectedDashboard(response.items[0]);
      }
    } catch (err) {
      // Handle different error types
      const error = err as { response?: { status?: number } };
      if (error?.response?.status === 403) {
        setError("You don't have permission to access any dashboards");
      } else if (error?.response?.status === 401) {
        setError("Please log in to access dashboards");
      } else {
        setError("Failed to load dashboards");
      }
      console.error("Error fetching permitted dashboards:", err);
    } finally {
      setLoading(false);
    }
  }, [selectedDashboard, i18n.language]);

  const getIframeUrl = useCallback(
    async (
      dashboardId: string,
      params: GetIframeUrlRequest = { params: {} },
    ) => {
      // Prevent multiple simultaneous requests for the same dashboard
      if (currentRequestRef.current === dashboardId) {
        return null;
      }

      try {
        currentRequestRef.current = dashboardId;
        setLoading(true);
        setError(null);
        const response = await metabaseService.getIframeUrl(
          dashboardId,
          params,
        );

        const secureUrl = response.iframeUrl.replace(/^http:\/\//i, "https://");
        // Only update if this is still the current request
        if (currentRequestRef.current === dashboardId) {
          setIframeUrl(secureUrl);
        }
        return secureUrl;
      } catch (err) {
        if (currentRequestRef.current === dashboardId) {
          // Handle permission errors specifically
          const error = err as { response?: { status?: number } };
          if (error?.response?.status === 403) {
            setError("You don't have permission to access this dashboard");
          } else {
            setError("Failed to load dashboard");
          }
          console.error("Error getting iframe URL:", err);
        }
        return null;
      } finally {
        if (currentRequestRef.current === dashboardId) {
          setLoading(false);
          currentRequestRef.current = null;
        }
      }
    },
    [],
  );

  const getFilteredDashboardUrl = useCallback(
    async (dashboardId: string, planYearId: string) => {
      // Prevent multiple simultaneous requests for the same dashboard
      const requestKey = `${dashboardId}-${planYearId}`;
      if (currentRequestRef.current === requestKey) {
        return null;
      }

      try {
        currentRequestRef.current = requestKey;
        setLoading(true);
        setError(null);
        const response = await metabaseService.getFilteredDashboardUrl(
          dashboardId,
          planYearId,
        );

        const secureUrl = response.iframeUrl.replace(/^http:\/\//i, "https://");
        // Only update if this is still the current request
        if (currentRequestRef.current === requestKey) {
          setIframeUrl(secureUrl);
        }
        return secureUrl;
      } catch (err) {
        if (currentRequestRef.current === requestKey) {
          // Handle permission errors specifically
          const error = err as { response?: { status?: number } };
          if (error?.response?.status === 403) {
            setError("You don't have permission to access this dashboard");
          } else {
            setError("Failed to load filtered dashboard");
          }
          console.error("Error getting filtered dashboard URL:", err);
        }
        return null;
      } finally {
        if (currentRequestRef.current === requestKey) {
          setLoading(false);
          currentRequestRef.current = null;
        }
      }
    },
    [],
  );

  const selectDashboard = useCallback((dashboard: MetabaseDashboard) => {
    setSelectedDashboard(dashboard);
    setIframeUrl(""); // Clear previous iframe URL
    // The useEffect will handle calling getIframeUrl
  }, []);

  const getDashboardByNumber = useCallback(
    (dashboardNumber: number) => {
      return dashboards.find(
        (d) => d.metabaseDashboardNumber === dashboardNumber,
      );
    },
    [dashboards],
  );

  useEffect(() => {
    fetchDashboards();
  }, [fetchDashboards]);

  useEffect(() => {
    if (selectedDashboard) {
      getIframeUrl(selectedDashboard.id);
    }
  }, [selectedDashboard, getIframeUrl]);

  return {
    dashboards,
    selectedDashboard,
    iframeUrl,
    loading,
    error,
    fetchDashboards,
    getIframeUrl,
    getFilteredDashboardUrl,
    selectDashboard,
    getDashboardByNumber,
  };
};
