import Image from "next/image"
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import { useSession } from "next-auth/react";
import { icons } from "#/assets/icons";
import { Stats, StatsType, } from "#/types";

export default function Statistics() {

    const { data: session, status } = useSession();

    const { data: stats, isLoading} = useQuery({
        enabled: status === 'authenticated',
        queryKey: ["stats", session?.user.access_token],
        queryFn: async () => {
            try {
                const response = await axios.get(
                    'https://private-docs-api.intside.co/statistics', {
                        headers: {
                            'Authorization': `Bearer ${session?.user.access_token}`
                        }
                    }
                )

                if(response.data) {
                    return response.data as Stats
                }  
            } catch (error) {
                console.error(error)
            }
        }
    })

    const statsData: StatsType[] = [
        { id: 1, title: 'Organisations', value: stats?.companies, icon: icons.companiesIcon, color: 'blue' },
        { id: 2, title: 'Utilisateurs', value: stats?.users, icon: icons.userIcon, color: 'blue' },
        { id: 3, title: 'Documents', value: stats?.documents, icon: icons.docummentTextIcon, color: 'blue' },
        { id: 4, title: 'Stockage', value: stats?.documents_size, icon: icons.archivesIcon, color: 'blue' }
      ];




    return(
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {statsData.map(({ id, title, value, icon }) => (
                <div key={id} className="w-full">
                    <div className="flex items-center rounded-xl border-2 border-blue-500 p-4 space-x-3">
                        <div 
                            className="flex items-center justify-center rounded-lg bg-[#E9F0FF] bg-opacity-25 p-2"
                            style={{ width: '54px', height: '54px' }}
                        >
                            <Image 
                                alt={title} 
                                src={icon} 
                                width={32} 
                                height={32} 
                                className="text-blue-500" 
                            />
                        </div>
                        <div className="ml-3">
                            <p className="text-sm text-gray-500 mb-0">{title}</p>
                            <p className="font-bold text-2xl mb-0">{ status === "loading" && isLoading ? "Chargement..." : value}</p>
                        </div>
                    </div>
                </div>
            ))}
        </div>
    )
}