import React, { useMemo, useState, useEffect } from 'react';
import { WorkoutSession, ExerciseType, Language, BodyWeightRecord } from '../types';
import { getWeightHistory } from '../services/weight';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar } from 'recharts';
import { t } from '../services/i18n';
import { useSession } from '../context/SessionContext';
import { TopBar } from './ui/TopBar';
import { BarChart2 } from 'lucide-react';

interface StatsProps {
    lang: Language;
}

const Stats: React.FC<StatsProps> = ({ lang }) => {
    const { sessions } = useSession();
    const [weightRecords, setWeightRecords] = useState<BodyWeightRecord[]>([]);

    useEffect(() => {
        const fetchWeights = async () => {
            const records = await getWeightHistory();
            setWeightRecords(records);
        };
        fetchWeights();
    }, []);

    const volumeData = useMemo(() => {
        const data: { date: string; work: number }[] = [];

        [...sessions].reverse().forEach(session => {
            const sessionWeight = session.userBodyWeight || 70;
            const work = session.sets.reduce((acc, set) => {
                let setWork = 0;
                const reps = set.reps || 0;
                const weight = set.weight || 0;
                if (set.type === ExerciseType.STRENGTH) {
                    setWork = weight * reps;
                } else if (set.type === ExerciseType.BODYWEIGHT) {
                    const percentage = set.bodyWeightPercentage || 100;
                    const effectiveBw = sessionWeight * (percentage / 100);
                    setWork = (effectiveBw + weight) * reps;
                } else if (set.type === ExerciseType.STATIC) {
                    setWork = 0;
                }
                return acc + Math.max(0, setWork);
            }, 0);

            if (work > 0) {
                const dateStr = new Date(session.startTime).toLocaleDateString(lang === 'ru' ? 'ru-RU' : 'en-US', { day: 'numeric', month: 'short' });
                const lastEntry = data[data.length - 1];
                if (lastEntry && lastEntry.date === dateStr) {
                    lastEntry.work += Math.round(work);
                } else {
                    data.push({ date: dateStr, work: Math.round(work) });
                }
            }
        });
        return data;
    }, [sessions, lang]);

    const sessionsCountData = useMemo(() => {
        const data: { date: string; sessions: number }[] = [];

        [...sessions].reverse().forEach(session => {
            const dateStr = new Date(session.startTime).toLocaleDateString(lang === 'ru' ? 'ru-RU' : 'en-US', { day: 'numeric', month: 'short' });
            const lastEntry = data[data.length - 1];
            if (lastEntry && lastEntry.date === dateStr) {
                lastEntry.sessions += 1;
            } else {
                data.push({ date: dateStr, sessions: 1 });
            }
        });

        return data;
    }, [sessions, lang]);

    const setsData = useMemo(() => {
        const data: { date: string; sets: number }[] = [];

        [...sessions].reverse().forEach(session => {
            const dateStr = new Date(session.startTime).toLocaleDateString(lang === 'ru' ? 'ru-RU' : 'en-US', { day: 'numeric', month: 'short' });
            const lastEntry = data[data.length - 1];
            if (lastEntry && lastEntry.date === dateStr) {
                lastEntry.sets += session.sets.length;
            } else {
                data.push({ date: dateStr, sets: session.sets.length });
            }
        });

        return data;
    }, [sessions, lang]);

    const weightData = useMemo(() => {
        const data: { date: string; weight: number }[] = [];

        [...weightRecords].reverse().forEach(record => {
            const dateStr = new Date(record.date).toLocaleDateString(lang === 'ru' ? 'ru-RU' : 'en-US', { day: 'numeric', month: 'short' });
            const lastEntry = data[data.length - 1];
            if (lastEntry && lastEntry.date === dateStr) {
                lastEntry.weight = record.weight;
            } else {
                data.push({ date: dateStr, weight: record.weight });
            }
        });

        return data;
    }, [weightRecords, lang]);

    if (sessions.length < 2) {
        return (
            <div className="p-8 text-center text-on-surface-variant flex flex-col items-center justify-center h-full">
                <p>{t('not_enough_data', lang)}</p>
            </div>
        )
    }

    return (
        <div className="h-full flex flex-col bg-surface">
            <TopBar title={t('progress', lang)} icon={BarChart2} />

            <div className="flex-1 overflow-y-auto p-4 space-y-6 pb-24 bg-surface">
                {/* Volume Chart */}
                <div className="bg-surface-container p-5 rounded-[24px] shadow-elevation-1 border border-outline-variant/20">
                    <div className="flex justify-between items-end mb-6">
                        <div>
                            <h3 className="text-title-medium font-medium text-on-surface">{t('volume_title', lang)}</h3>
                            <p className="text-xs text-on-surface-variant mt-1">{t('volume_subtitle', lang)}</p>
                        </div>
                    </div>
                    <div className="h-64 min-h-64 w-full">
                        <ResponsiveContainer width="100%" height={256}>
                            <LineChart data={volumeData}>
                                <CartesianGrid strokeDasharray="3 3" stroke="#49454F" vertical={false} opacity={0.5} />
                                <XAxis dataKey="date" stroke="#CAC4D0" fontSize={12} tickLine={false} axisLine={false} dy={10} />
                                <YAxis stroke="#CAC4D0" fontSize={12} tickLine={false} axisLine={false} tickFormatter={(val) => `${(val / 1000).toFixed(1)}k`} />
                                <Tooltip
                                    contentStyle={{ backgroundColor: '#2B2930', borderColor: '#49454F', color: '#E6E0E9', borderRadius: '12px' }}
                                    itemStyle={{ color: '#D0BCFF' }}
                                    formatter={(val: number) => [`${val.toLocaleString()} kg`, t('volume_title', lang)]}
                                />
                                <Line type="monotone" dataKey="work" stroke="#D0BCFF" strokeWidth={3} dot={{ r: 4, fill: '#D0BCFF' }} activeDot={{ r: 6 }} />
                            </LineChart>
                        </ResponsiveContainer>
                    </div>
                </div>

                {/* Sessions Count Chart */}
                <div className="bg-surface-container p-5 rounded-[24px] shadow-elevation-1 border border-outline-variant/20">
                    <h3 className="text-title-medium font-medium text-on-surface mb-6">{t('sessions_count_title', lang)}</h3>
                    <div className="h-64 min-h-64 w-full">
                        <ResponsiveContainer width="100%" height={256}>
                            <BarChart data={sessionsCountData}>
                                <CartesianGrid strokeDasharray="3 3" stroke="#49454F" vertical={false} opacity={0.5} />
                                <XAxis dataKey="date" stroke="#CAC4D0" fontSize={12} tickLine={false} axisLine={false} dy={10} />
                                <YAxis stroke="#CAC4D0" fontSize={12} tickLine={false} axisLine={false} allowDecimals={false} />
                                <Tooltip
                                    contentStyle={{ backgroundColor: '#2B2930', borderColor: '#49454F', color: '#E6E0E9', borderRadius: '12px' }}
                                    cursor={{ fill: 'rgba(255,255,255,0.05)' }}
                                />
                                <Bar dataKey="sessions" fill="#4FD1C5" radius={[4, 4, 0, 0]} />
                            </BarChart>
                        </ResponsiveContainer>
                    </div>
                </div>

                {/* Sets Chart */}
                <div className="bg-surface-container p-5 rounded-[24px] shadow-elevation-1 border border-outline-variant/20">
                    <h3 className="text-title-medium font-medium text-on-surface mb-6">{t('sets_title', lang)}</h3>
                    <div className="h-64 min-h-64 w-full">
                        <ResponsiveContainer width="100%" height={256}>
                            <BarChart data={setsData}>
                                <CartesianGrid strokeDasharray="3 3" stroke="#49454F" vertical={false} opacity={0.5} />
                                <XAxis dataKey="date" stroke="#CAC4D0" fontSize={12} tickLine={false} axisLine={false} dy={10} />
                                <YAxis stroke="#CAC4D0" fontSize={12} tickLine={false} axisLine={false} />
                                <Tooltip
                                    contentStyle={{ backgroundColor: '#2B2930', borderColor: '#49454F', color: '#E6E0E9', borderRadius: '12px' }}
                                    cursor={{ fill: 'rgba(255,255,255,0.05)' }}
                                />
                                <Bar dataKey="sets" fill="#CCC2DC" radius={[4, 4, 0, 0]} />
                            </BarChart>
                        </ResponsiveContainer>
                    </div>
                </div>

                {/* Body Weight Chart */}
                <div className="bg-surface-container p-5 rounded-[24px] shadow-elevation-1 border border-outline-variant/20">
                    <h3 className="text-title-medium font-medium text-on-surface mb-6">{t('weight_title', lang)}</h3>
                    <div className="h-64 min-h-64 w-full">
                        <ResponsiveContainer width="100%" height={256}>
                            <LineChart data={weightData}>
                                <CartesianGrid strokeDasharray="3 3" stroke="#49454F" vertical={false} opacity={0.5} />
                                <XAxis dataKey="date" stroke="#CAC4D0" fontSize={12} tickLine={false} axisLine={false} dy={10} />
                                <YAxis domain={['auto', 'auto']} stroke="#CAC4D0" fontSize={12} tickLine={false} axisLine={false} />
                                <Tooltip
                                    contentStyle={{ backgroundColor: '#2B2930', borderColor: '#49454F', color: '#E6E0E9', borderRadius: '12px' }}
                                    itemStyle={{ color: '#6EE7B7' }}
                                    formatter={(val: number) => [`${val} kg`, t('weight_kg', lang)]}
                                />
                                <Line type="monotone" dataKey="weight" stroke="#6EE7B7" strokeWidth={3} dot={{ r: 4, fill: '#6EE7B7' }} activeDot={{ r: 6 }} />
                            </LineChart>
                        </ResponsiveContainer>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Stats;
