'use client';

import { useState, use, useEffect } from 'react';

import { Player } from '../../../types';
import { positionMap } from '../../../positionMap';
import { teamsMap } from '../../../teamsMap';

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

export default function TeamRoster({ params }: { params: Promise<{ id: string }> }) {
    const [roster, setRoster] = useState<Player[]>([]);
    const { id } = use(params);

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

    async function fetchTeamRoster() {
        try {
            const response = await fetch(`${process.env.NEXT_PUBLIC_BASE_API_URL}/teams/${id}`);
            const data = await response.json();
            if (data.length > 0) {
                setRoster(data);
            } else {
                setInErrorState(true);
                setErrorCode('Invalid Team ID - please try another team from dropdown menu.');
            }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        } catch (error: any) {
            console.error('Error fetching team roster: ', error);
            setInErrorState(true);
            setErrorCode(error);
        }
    }

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

    function renderNickname(firstname: string | undefined, usesname: string | undefined) {
        return firstname === usesname ? "" : `"${usesname}" `;
    }

    function playerNameWithNickname(
        firstname: string | undefined,
        usesname: string | undefined,
        lastname: string | undefined
    ) {
        return `${firstname} ${renderNickname(firstname, usesname)}${lastname}`;
    }
    function Roster() {
        return roster.map((player: Player, index) => {
            return (
                <tr key={index} className="border-b border-gray-100 hover:bg-gray-50">
                    <td className="py-3 px-4">
                        [{player.number}] <a href={`/player/${player.playerid}`} className="text-[#0000ee]">
                            {playerNameWithNickname(player.firstname, player.usesname, player.lastname)}
                        </a>
                    </td>
                    <td className="py-3 px-4">
                        { positionMap[player.position] }
                    </td>
                </tr>
            )
        });
    }

    return (
        <>
            <NavBar />
            <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 p-8" style={{ marginTop: 50 }}>
                <div className="max-w-6xl mx-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>
                        :
                        <></>
                    }
                    <div className="bg-white rounded-lg shadow-lg p-6 mb-6">
                        <h1 className="text-4xl">{teamsMap[parseInt(id)]} Team Roster:</h1>
                        <table className="w-full">
                            <thead>
                                <tr className="border-b-2 border-gray-200">
                                    <th className="text-left py-3 px-4 font-semibold text-gray-700">Name:</th>
                                    <th className="text-left py-3 px-4 font-semibold text-gray-700">Position:</th>
                                </tr>
                            </thead>
                            <tbody>
                                {Roster()}
                            </tbody>
                        </table>
                        
                    </div>
                </div>
            </div>
            <Footer />
        </>
    )
}