import { useState, useCallback } from 'react';
import { api } from '@/lib/api';
import { ENDPOINTS } from '@/constants/endpoints';
import type { DashboardOverview, ActivityItem, ApiResponse } from '@/types';
import i18n from "@/lib/i18n";

export function useDashboard() {
  const [overview, setOverview] = useState<DashboardOverview | null>(null);
  const [activity, setActivity] = useState<ActivityItem[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchOverview = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const response: ApiResponse<DashboardOverview> = await api.get(ENDPOINTS.DASHBOARD.OVERVIEW);
      if (response.success && response.data) {
        setOverview(response.data);
      } else {
        throw new Error(response.message || i18n.t('hooks.useDashboard.text_1'));
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : i18n.t('hooks.useDashboard.text_2'));
    } finally {
      setIsLoading(false);
    }
  }, []);

  const fetchActivity = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const response: ApiResponse<ActivityItem[]> = await api.get(ENDPOINTS.DASHBOARD.ACTIVITY);
      if (response.success && response.data) {
        setActivity(Array.isArray(response.data) ? response.data : []);
      } else {
        throw new Error(response.message || i18n.t('hooks.useDashboard.text_3'));
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : i18n.t('hooks.useDashboard.text_4'));
    } finally {
      setIsLoading(false);
    }
  }, []);

  const forceFetchPrices = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      await api.post(ENDPOINTS.GOLD.FETCH_PRICES);
      await fetchOverview();
    } catch (err) {
      setError(err instanceof Error ? err.message : i18n.t('hooks.useDashboard.text_5'));
      setIsLoading(false);
    }
  }, [fetchOverview]);

  return {
    overview,
    activity,
    isLoading,
    error,
    fetchOverview,
    fetchActivity,
    forceFetchPrices,
  };
}