'use client'

import { PieChartComponent } from '@/app/components/PieChartComponent';
import { useQuery } from '@tanstack/react-query';
import { getUserFilesInfo } from '@/app/actions/action';
import { useState, useEffect } from 'react';
import { convertBytes } from '@/app/lib/convertBytes';


type FilesInfo = {
	totalSize: number;
	totalCount: number;
	imageQuantity: number;
	videoQuantity: number;
	audioQuantity: number;
	documentQuantity: number;
	imageSize: number;
	videoSize: number;
	audioSize: number;
	documentSize: number;
};

export default function MyContentPieChart() {
	const [filesCount, setFilesCount] = useState([
		{ name: 'images', value: 0, color: '#f08c00' },
		{ name: 'videos', value: 0, color: '#2f9e44' },
		{ name: 'audios', value: 0, color: '#1971c2' },
		{ name: 'documents', value: 0, color: '#a561e6' },
	]);

	const {
		data: filesInfo,
		isLoading,
		isError,
		error,
	} = useQuery<{
		all_files_size: number,
		all_files_quantity: number,
		images_quantity: number,
		videos_quantity: number,
		audios_quantity: number,
		documents_quantity: number,
		images_size: number,
		videos_size: number,
		audios_size: number,
		documents_size: number,
	}, Error, FilesInfo>({
		queryKey: ['userFilesInfo'],
		queryFn: getUserFilesInfo,
		select: (data): FilesInfo => {
			if (!data) {
				return {
					totalSize: 0,
					totalCount: 0,
					imageQuantity: 0,
					videoQuantity: 0,
					audioQuantity: 0,
					documentQuantity: 0,
					imageSize: 0,
					videoSize: 0,
					audioSize: 0,
					documentSize: 0,
				}
			}

			return {
				totalSize: data.all_files_size,
				totalCount: data.all_files_quantity,
				imageQuantity: data.images_quantity,
				videoQuantity: data.videos_quantity,
				audioQuantity: data.audios_quantity,
				documentQuantity: data.documents_quantity,
				imageSize: data.images_size,
				videoSize: data.videos_size,
				audioSize: data.audios_size,
				documentSize: data.documents_size,
			}
		},
	});

	useEffect(() => {
		setFilesCount([
			{
				name: 'images-few',
				value: filesInfo?.imageSize ? filesInfo?.imageSize : 0,
				color: '#f08c00'
			},
			{
				name: 'videos',
				value: filesInfo?.videoSize ? filesInfo?.videoSize : 0,
				color: '#2f9e44'
			},
			{
				name: 'audios',
				value: filesInfo?.audioSize ? filesInfo?.audioSize : 0,
				color: '#1971c2'
			},
			{
				name: 'documents',
				value: filesInfo?.documentSize ? filesInfo?.documentSize : 0,
				color: '#a561e6'
			},
		])
	}, [filesInfo]);

	return (
		<div className="protection-overview">
			<PieChartComponent data={filesCount} show={filesInfo?.totalSize ? convertBytes(filesInfo?.totalSize) : 0} />
		</div>
	)
}