import { OrganizationDto } from "@/shared/dto/organization/organizationDto";
import { getOrganizations } from "@/shared/services/organizationsService";
import { useQuery } from "@tanstack/react-query";
import Cookies from "js-cookie";
import { toast } from "sonner";
import { useOrganizations } from "./useOrganizations";

// Types for dashboard data
export interface DashboardStats {
  totalOrganizations: number;
  activeOrganizations: number;
  inactiveOrganizations: number;
  pendingRequests: number;
  orgAdmins: number;
  recentActivities: Activity[];
  percentChanges: {
    orgs: number;
    active: number;
    inactive: number;
    pending: number;
    admins: number;
  };
}

export interface Activity {
  id: string;
  type: string;
  description: string;
  user: string;
  timestamp: string;
  entity: string;
  entityId: string;
}

// Mock data
const mockDashboardData: DashboardStats = {
  totalOrganizations: 48,
  activeOrganizations: 35,
  inactiveOrganizations: 13,
  pendingRequests: 7,
  orgAdmins: 21,
  recentActivities: [
    {
      id: "1",
      type: "CREATE",
      description: "Created new organization",
      user: "John Doe",
      timestamp: "2023-07-15T10:30:00Z",
      entity: "Woreda 01",
      entityId: "org-1",
    },
    {
      id: "2",
      type: "UPDATE",
      description: "Updated organization status",
      user: "Jane Smith",
      timestamp: "2023-07-14T14:45:00Z",
      entity: "Woreda 02",
      entityId: "org-2",
    },
    {
      id: "3",
      type: "DELETE",
      description: "Deleted organization",
      user: "Admin User",
      timestamp: "2023-07-13T09:15:00Z",
      entity: "Test Org",
      entityId: "org-3",
    },
    {
      id: "4",
      type: "CREATE",
      description: "Added admin user",
      user: "System",
      timestamp: "2023-07-12T16:20:00Z",
      entity: "Samuel Bekele",
      entityId: "user-1",
    },
    {
      id: "5",
      type: "UPDATE",
      description: "Changed organization settings",
      user: "Jane Smith",
      timestamp: "2023-07-11T11:05:00Z",
      entity: "Yeka Subcity",
      entityId: "org-4",
    },
  ],
  percentChanges: {
    orgs: 12.5,
    active: 8.2,
    inactive: -3.7,
    pending: -15.4,
    admins: 5.6,
  },
};

const fetchDashboardStats = async (
  totalOrganizations: number
): Promise<DashboardStats> => {
  // Use mock data for now, but replace totalOrganizations with the actual count
  const dashboardData = { ...mockDashboardData };
  dashboardData.totalOrganizations =
    totalOrganizations || dashboardData.totalOrganizations;
  return dashboardData;
};

const fetchRecentOrganizations = async (): Promise<OrganizationDto[]> => {
  try {
    const tenantKey = Cookies.get("tenant-key");
    if (!tenantKey) {
      console.error("No tenant key found");
      return [];
    }

    const headers = {
      tenantKey,
      unitId: Cookies.get("unit-id") || undefined,
    };

    const { data } = await getOrganizations({
      orderBy: "createdAt",
      take: 5,
    });

    return data.items;
  } catch (error) {
    console.error("Error fetching recent organizations:", error);
    return [];
  }
};

export const useDashboardData = () => {
  const { organizationsResponse } = useOrganizations("Org");

  const {
    data: stats,
    isLoading: isStatsLoading,
    isError: isStatsError,
    refetch: refetchStats,
  } = useQuery({
    queryKey: ["dashboardStats"],
    queryFn: async () => {
      try {
        const totalOrganizations = organizationsResponse?.count || 0;
        return await fetchDashboardStats(totalOrganizations);
      } catch (error) {
        console.error("Failed to fetch dashboard statistics:", error);
        toast.error("Failed to fetch dashboard statistics");
        return mockDashboardData;
      }
    },
    staleTime: 5 * 60 * 1000, // 5 minutes
    retry: 1,
  });

  const {
    data: recentOrgs,
    isLoading: isOrgsLoading,
    isError: isOrgsError,
    refetch: refetchOrgs,
  } = useQuery({
    queryKey: ["recentOrganizations"],
    queryFn: async () => {
      try {
        return await fetchRecentOrganizations();
      } catch (error) {
        console.error("Failed to fetch recent organizations:", error);
        toast.error("Failed to fetch recent organizations");
        return [];
      }
    },
    staleTime: 2 * 60 * 1000, // 2 minutes
    retry: 1,
  });

  const isLoading = isStatsLoading || isOrgsLoading;
  const isError = isStatsError || isOrgsError;

  const refetch = () => {
    refetchStats();
    refetchOrgs();
  };

  const orgCount = organizationsResponse?.count;

  return {
    stats: stats || orgCount,
    recentOrgs: recentOrgs || [],
    isLoading,
    isError,
    refetch,
  };
};
