import { getSession } from 'next-auth/react';
import { use, useEffect, useMemo, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';

interface DataPoint {
  date: string;
  value: number;
}

interface ChartDataSet {
  label: string;
  data: number[];
}
interface ChartData {
  labels: string[];
  datasets: ChartDataSet[];
}

const useAvgChartData = () => {
    const performanceData = useSelector((state: any) => state.avgPerformance.Performance);
    console.log("performanceData", performanceData);
    
    function getUniqueDates(dates: string[]) {
        // Create a Set to store unique dates
        const uniqueDates = new Set(dates);
        // Convert the Set back to an array and sort it
        return Array.from(uniqueDates).sort();
    }

    const getDataPoint = (jsonData: any, title: string, basePrices: any) => {
        const basePrice =
        basePrices.find((price: any) => price.title === title)?.value ?? 0;
        // Extract values from the array
        const cData = jsonData.map((point: DataPoint) => {
            const date = new Date(point.date);
            const formattedDate = date.toISOString().split('T')[0]; // Format the date to 'YYYY-MM-DD'
                return {
                    date: formattedDate,
                    value: point.value,
                };
            });
        const dataPoints = cData.map((point: DataPoint) => {
            const diffVal = point.value - basePrice;
            return { value: (diffVal / basePrice) * 100, date: point.date };
        });

        return {
            label: title,
            data: dataPoints,
        };
    };

    const prepareChartData = (charts: any, labels: string[]) => {
        return charts.map((cart: any) => {
            const newDP: number[] = [];
            let preValue: number = 0;
            getUniqueDates(labels).forEach((date) => {
                const hasD = cart.data.find((d: any) => d.date === date);
                if (hasD) {
                newDP.push(hasD.value);
                preValue = hasD.value;
                } else {
                newDP.push(preValue);
                }
            });

            return {
                label: cart.label,
                data: newDP,
            };
        });
    };

    const formatDate = (date: string) => {
        const d = new Date(date);
        const day = String(d.getDate()).padStart(2, '0');
        const month = String(d.getMonth() + 1).padStart(2, '0'); // Months are zero-based
        const year = d.getFullYear();

        return `${day}.${month}.${year}`;
    };


    const getAvgChartData = (selectedPeriod: string, watchlistItems: any = []) => {
        const basePrices: any = [];
        if (performanceData && performanceData.length > 0) {
            let carts: any[] = [];
            let labels: string[] = [];
            let baseFundIndex: number = -1;
            let baseFundLength: number = -1;
            let baseDate: string = '';
            const title = performanceData.map((performance: any, index: number) => {
                return { title:  performance.fundName || watchlistItems[index]?.fundName || `Fund ${index + 1}` };
            });
            
            performanceData.map((performance: any, i: number) => {
                if (performance && performance[selectedPeriod]) {
                    const jsonData = JSON.parse(performance[selectedPeriod]);
                    const oldest = jsonData.length
                    ? jsonData.reduce((prev: DataPoint, curr: DataPoint) =>
                        new Date(prev.date) < new Date(curr.date) ? prev : curr
                    )
                    : null;
                    if (
                        baseFundLength === -1 ||
                        (baseFundLength <= jsonData.length && jsonData.length > 0)
                    ) {
                        baseFundIndex = i;
                        baseFundLength = jsonData.length;
                        baseDate = oldest ? oldest.date : '';
                    }
                }
            });
    
            performanceData.map((performance: any, i: number) => {
                if (performance && performance[selectedPeriod]) {
                    const jsonData = JSON.parse(performance[selectedPeriod]).filter(
                        (point: DataPoint) => {
                            const date = new Date(point.date);
                            const bdate = new Date(baseDate);
                            return date >= bdate;
                        }
                    );
                    const oldest =
                    jsonData.length > 0 ? (
                        jsonData.reduce((prev: DataPoint, curr: DataPoint) =>
                            new Date(prev.date) < new Date(curr.date) ? prev : curr
                        )
                    ) : (
                        <></>
                    );
                    basePrices.push({
                        title: title[i].title,
                        value: oldest?.value ?? 0,
                    });
                }
            });
    
            performanceData.map((performance: any, i: number) => {
                if (
                    performance &&
                    performance[selectedPeriod] &&
                    performance[selectedPeriod].length > 0
                ) {
                    const jsonData = JSON.parse(performance[selectedPeriod]).filter(
                        (point: DataPoint) => {
                            const date = new Date(point.date);
                            const bdate = new Date(baseDate);
                            return date >= bdate;
                        }
                    );
                    if (baseFundIndex === i) {
                        labels.push(
                            ...jsonData.map((point: DataPoint) => {
                                const date = new Date(point.date);
                                const formattedDate = date.toISOString().split('T')[0];
                                return formattedDate;
                            })
                        );
                    }
                    const dataPoint = getDataPoint(jsonData, title[i].title, basePrices);
            
                    carts.push({
                        label: dataPoint.label,
                        data: dataPoint.data,
                    });
                }
                return performance;
            });
        
            const td = {
                labels: getUniqueDates(labels).map((item) => formatDate(item)),
                datasets: prepareChartData(carts, labels),
            };
            console.log("carts", td);
            
            
            return {
                basePrices,
                chartData: td
            };
        }
        return {
            basePrices: [],
            chartData: {
                labels: [],
                datasets: [],
            }
        };
    };

    return {
        getAvgChartData
    };
}

export default useAvgChartData;