'use client';

import { useState, use, useEffect } from 'react';
import { useMediaQuery } from 'react-responsive';
import useResize from '../../../hooks/resizeHook';

import { Player, BatterStats, PitcherStats, Metrics } from '../../../types';

import {
    PlayerCard,
    NavBar,
    Footer,
    PitcherStatsTable,
    BatterStatsTable,
    MetricsCard
} from '../../../components';
import { Card, Typography } from '@mui/material';
import CardContent from '@mui/material/CardContent';

export default function PlayerInfo({ params }: { params: Promise<{ playerid: string }> }) {
    const isMobile = useMediaQuery({ maxWidth: 600 });
    useResize();

    const [player, setPlayer] = useState<Player>();
    const { playerid } = use(params);
    const [pitcherStats, setPitcherStats] = useState<PitcherStats[]>([]);
    const [batterStats, setBatterStats] = useState<BatterStats[]>([]);

    const [playerMetrics, setPlayerMetrics] = useState<Metrics[]>([]);
    const [loadingMetrics, setLoadingMetrics] = useState(true);

    const [inErrorState, setInErrorState] = useState(false);
    const [errorCode, setErrorCode] = useState('');

    async function fetchPlayer() {
        try {
            const response = await fetch(`${process.env.NEXT_PUBLIC_BASE_API_URL}/player/${ playerid }`);
            const data = await response.json();
            if (data.length > 0) {
                setPlayer(data[0]);
            } else {
                setInErrorState(true);
                setErrorCode('Invalid Player ID - please choose another player from searchbar or a Team roster.');
            }
        } catch (error: any) {
            console.error('Error fetching player: ', error);
            setInErrorState(true);
            setErrorCode(error);
        }
    }

    useEffect(() => {
        // eslint-disable-next-line react-hooks/set-state-in-effect
        fetchPlayer();
    }, [playerid]);

    // Player statistics functions
    function isPitcher(position: number | undefined) {
        return position == 1 || position == 11 || position == 12 ? true: false;
    }

    useEffect(() => {
        fetchPlayerStats();
        fetchPlayerMetrics();
    }, [player]);

    async function fetchPlayerStats() {
        if (player?.position == undefined || player?.position == 0) {
            return;
        }
        try {
            const batterOrPitcherApi = isPitcher(player?.position) ?
                `${process.env.NEXT_PUBLIC_BASE_API_URL}/pitcher/${playerid}` :
                `${process.env.NEXT_PUBLIC_BASE_API_URL}/batter/${playerid}`;

            const response = await fetch(batterOrPitcherApi);
            const data = await response.json();

            // Parse data to check for players that did multi-team seasons
            const yearsInData: number[] = [];
            let multiTeamSeasonData: any[] = [];
            let spliceIndex = 0;
            let foundEdgeCase = false;
            data.forEach((entry: any, index: number) => {
                if (!yearsInData.includes(entry.yearid)) {
                    yearsInData.push(entry.yearid);
                } else {
                    // Found an edge case player, get the year with multi-team play
                    foundEdgeCase = true;
                    spliceIndex = index;
                    multiTeamSeasonData = data.filter((e: any) => {
                        return e.yearid === entry.yearid;
                    });
                }
            });

            // When an edge case is found, total up the multi-year data
            if (foundEdgeCase) {
                // Common values
                let totalGames: number = 0;
                let totalB1: number = 0;
                let totalB2: number = 0;
                let totalB3: number = 0;
                let totalHR: number = 0;
                let totalStrikeOuts: number = 0;
                let totalIbb: number = 0;
                let totalUbb: number = 0;

                // Pitcher values
                let totalGamesStarted: number = 0;
                let totalWins: number = 0;
                let totalLosses: number = 0;
                let totalSaves: number = 0;
                let totalOuts: number = 0;
                let totalEr: number = 0;

                // Batter values
                let totalAtBats: number = 0;
                let totalHbp: number = 0;

                multiTeamSeasonData.forEach((team) => {
                    totalGames += team.g;
                    totalB1 += team.b1;
                    totalB2 += team.b2;
                    totalB3 += team.b3;
                    totalHR += team.hr;
                    totalStrikeOuts += team.so;
                    totalIbb += team.ibb;
                    totalUbb += team.ubb;

                    if (isPitcher(player.position)) {
                        totalGamesStarted += team.gs;
                        totalWins += team.w;
                        totalLosses += team.l;
                        totalSaves += team.sv;
                        totalOuts += team.outs;
                        totalEr += team.er;
                    } else {
                        totalAtBats += team.ab;
                        totalHbp += team.hbp;
                    }
                });
                let pitcherTotals: PitcherStats = {
                    playerid: 0,
                    yearid: '',
                    levelid: 0,
                    teamid: 0,
                    g: 0,
                    gs: 0,
                    w: 0,
                    l: 0,
                    sv: 0,
                    outs: 0,
                    b1: 0,
                    b2: 0,
                    b3: 0,
                    hr: 0,
                    so: 0,
                    er: 0,
                    ibb: 0,
                    ubb: 0
                };
                let batterTotals: BatterStats = {
                    playerid: 0,
                    yearid: '',
                    levelid: 0,
                    teamid: 0,
                    g: 0,
                    ab: 0,
                    b1: 0,
                    b2: 0,
                    b3: 0,
                    hr: 0,
                    ubb: 0,
                    hbp: 0,
                    so: 0,
                    ci: 0,
                    ibb: 0,
                    sh: 0,
                    sf: 0,
                    sb: 0,
                    cs: 0,
                    pa: 0,
                    r: 0,
                    rbi: 0
                };
                if (isPitcher(player.position)) {
                    pitcherTotals.yearid = `${multiTeamSeasonData[0]?.yearid} Total`;
                    pitcherTotals.g = totalGames;
                    pitcherTotals.b1 = totalB1;
                    pitcherTotals.b2 = totalB2;
                    pitcherTotals.b3 = totalB3;
                    pitcherTotals.hr = totalHR;
                    pitcherTotals.so = totalStrikeOuts;
                    pitcherTotals.ibb = totalIbb;
                    pitcherTotals.ubb = totalUbb;
                    pitcherTotals.gs = totalGamesStarted;
                    pitcherTotals.w = totalWins;
                    pitcherTotals.l = totalLosses;
                    pitcherTotals.sv = totalSaves;
                    pitcherTotals.outs = totalOuts;
                    pitcherTotals.er = totalEr;
                    // Insert the pitcher's totals into the row after the multi-teams years
                    data.splice(spliceIndex + 1, 0, pitcherTotals);
                } else {
                    batterTotals.yearid = `${multiTeamSeasonData[0]?.yearid} Total`;
                    batterTotals.g = totalGames;
                    batterTotals.b1 = totalB1;
                    batterTotals.b2 = totalB2;
                    batterTotals.b3 = totalB3;
                    batterTotals.hr = totalHR;
                    batterTotals.so = totalStrikeOuts;
                    batterTotals.ibb = totalIbb;
                    batterTotals.ubb = totalUbb;
                    batterTotals.ab = totalAtBats;
                    batterTotals.hbp = totalHbp;
                    // Insert the batter's totals into the row after the multi-teams years
                    data.splice(spliceIndex + 1, 0, batterTotals);
                }
            }

            isPitcher(player.position) ? setPitcherStats(data) : setBatterStats(data);
        } catch (error) {
            console.error('Error fetching player: ', error);
        }
    }

    // Player Metrics functions
    async function fetchPlayerMetrics() {
        if (player?.position == undefined || player?.position == 0) {
            return;
        }
        try {
            const batterOrPitcherApi = isPitcher(player?.position) ?
                `${process.env.NEXT_PUBLIC_BASE_API_URL}/metrics/pitcher/${playerid}` :
                `${process.env.NEXT_PUBLIC_BASE_API_URL}/metrics/batter/${playerid}`;

            const response = await fetch(batterOrPitcherApi);
            const data = await response.json();
            setPlayerMetrics(data);
            setLoadingMetrics(false);
        } catch (error) {
            console.error('Error fetching player: ', error);
        }
    }

    return (
        <>
            <NavBar />
            <div className={`min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 ${ isMobile ? 'py-8 px-2': 'p-8'} grid content-center`} style={{ overflow: 'auto' }}>
                {inErrorState ?
                    <div className="flex content-center">
                        <Card sx={{ maxWidth: 345 }}>
                            <CardContent className="bg-red-100">
                                <Typography>
                                    <b>ERROR:</b> {errorCode}
                                </Typography>
                            </CardContent>
                        </Card>
                    </div>
                    :
                    <></>
                }
                {inErrorState ?
                    <></>
                    :
                    isMobile ?
                        <div className="max-w-sm mx-auto" style={{ marginTop: 50 }}>
                            <PlayerCard player={player} />
                                    <div className="flex flex-col">
                                        <div style={{ paddingTop: 15, marginBottom: 15 }}>
                                    {isPitcher(player?.position) ? <PitcherStatsTable rows={pitcherStats} /> : <BatterStatsTable rows={batterStats} />}
                                </div>
                                <div style={{ marginBottom: 30 }}>
                                    <MetricsCard metrics={playerMetrics} loadingMetrics={loadingMetrics} isPitcher={isPitcher(player?.position)} />
                                </div>
                            </div>
                        </div>
                        :
                        <div className="max-w-6xl mx-auto flex">
                            <PlayerCard player={player} />
                            <div className="flex flex-col">
                                <div style={{ paddingLeft: 15 }}>
                                    {isPitcher(player?.position) ? <PitcherStatsTable rows={pitcherStats} /> : <BatterStatsTable rows={batterStats} />}
                                </div>
                                <div style={{ paddingLeft: 15, paddingTop: 30 }}>
                                    <MetricsCard metrics={playerMetrics} loadingMetrics={loadingMetrics} isPitcher={isPitcher(player?.position)} />
                                </div>
                            </div>
                        </div>
                    }
                </div>
            <Footer />
        </>
    )
}