import "../style/team_panel.css"
import {Member, MemberRole, Team, TeamInfo} from "../model/Team"
import {useNavigate, useParams} from "react-router-dom"
import {useAppFetcher, useUser} from "../App.tsx";
import {useEffect, useState} from "react";

export default function TeamPanelPage() {
    const fetcher = useAppFetcher()
    const { teamId } = useParams()
    const [team,setTeam ] = useState<Team>()
    const [user] = useUser()
    useEffect(() => {
        async function init(){
            const infoResponse = await fetcher.fetchAPIGet("teams/"+teamId)
            const teamInfo : TeamInfo = await infoResponse.json()
            const membersResponse = await fetcher.fetchAPIGet("teams/"+teamId+"/members")
            const members : Member[] = await membersResponse.json()
            setTeam({info:teamInfo, members:members})
        }

        if(team === undefined){
            init()
        }

    }, [fetcher,team]);
    if(team === undefined){
        return <p>Chargement ...</p>
    }

    const isCoach = team.members.some(m=>m.user.id === user!.id && m.role === MemberRole.COACH)
    return (
        <TeamPanel
            team={{ info: team.info, members: team.members }}
            currentUserId={user!.id}
            isCoach={isCoach}
        />
    )
}

function TeamPanel({
    isCoach,
    team,
    currentUserId,
}: {
    isCoach: boolean
    team: Team
    currentUserId: number
}) {
    return (
        <div id="main-div">
            <TeamDisplay team={team.info} />

            {isCoach && <CoachOptions id={team.info.id} userId={currentUserId} />}

            <MembersDisplay
                members={team.members}
                isCoach={isCoach}
                idTeam={team.info.id}
                currentUserId={currentUserId}
            />
        </div>
    )
}

function TeamDisplay({ team }: { team: TeamInfo }) {
    return (
        <div id="team-info">
            <div id="first-part">
                <h1 id="team-name">{team.name}</h1>
                <img id="logo" src={team.picture} alt="Logo d'équipe" />
            </div>
            <div id="colors">
                <div id="colorsTitle">
                    <p>Couleur principale</p>
                    <p>Couleur secondaire</p>
                </div>
                <div id="actual-colors">
                    <ColorDisplay color={team.mainColor} />
                    <ColorDisplay color={team.secondColor} />
                </div>
            </div>
        </div>
    )
}

function ColorDisplay({ color }: { color: string }) {
    return <div className="square" style={{ backgroundColor: color }} />
}

function CoachOptions({ id,userId }: { id: number,userId:number }) {
    const navigate = useNavigate()
    const fetcher = useAppFetcher()
    return (
        <div>
            <button
                id="delete"
                onClick={async () => {
                    const res = confirm("Êtes-vous sûr de supprimer cette équipe?")
                    if (res) {
                        await fetcher.fetchAPI(
                            "team/" + id + "/members/" + userId,
                            {},
                            "DELETE"
                        )
                        navigate("/")
                    }
                }
                }>
                Supprimer
            </button>
        </div>
    )
}

function MembersDisplay({
    members,
    isCoach,
    idTeam,
    currentUserId,
}: {
    members: Member[]
    isCoach: boolean
    idTeam: number
    currentUserId: number
}) {
    const listMember = members.map((member) => (
        <MemberDisplay
            member={member}
            isCoach={isCoach}
            idTeam={idTeam}
            currentUserId={currentUserId}
        />
    ))
    const navigate = useNavigate()
    return (
        <div id="members">
            <div id="head-members">
                <h2>Membres :</h2>
                {isCoach && (
                    <button
                        id="add-member"
                        onClick={() =>
                            navigate("/team/"+idTeam+"/addMember")
                        }>
                        +
                    </button>
                )}
            </div>
            {listMember}
        </div>
    )
}

function MemberDisplay({
    member,
    isCoach,
    idTeam,
    currentUserId,
}: {
    member: Member
    isCoach: boolean
    idTeam: number
    currentUserId: number
}) {
    const fetcher = useAppFetcher()
    const navigate = useNavigate()

    return (
        <div className="member">
            <img
                id="profile-picture"
                src={member.user.profilePicture}
                alt="Photo de profile"
            />
            <p>{member.user.name}</p>
            <p>{member.role === MemberRole.COACH ? "Coach" : "Joueur"}</p>
            <p>{member.user.email}</p>
            {isCoach && currentUserId !== member.user.id && (
                <button
                    id="delete"
                    onClick={() =>
                        confirm("Êtes-vous sûr de quitter cette équipe?")
                            ? (fetcher.fetchAPI(
                                    "team/"+idTeam+"/members/"+member.user.id,
                                    {},
                                    "DELETE"
                                )
                            )
                            : {}
                    }>
                    Retirer
                </button>
            )}
            {isCoach && currentUserId == member.user.id && (
                <button
                    id="delete"
                    onClick={async () => {

                        const res = confirm(
                            "Êtes-vous sûr de retirer ce membre de l'équipe?"
                        )
                        if (res) {
                            await fetcher.fetchAPI(
                                "team/" + idTeam + "/members/" + member.user.id,
                                {},
                                "DELETE"
                            )
                            navigate("/")
                        }
                    }
                    }>
                    Quitter
                </button>
            )}
        </div>
    )
}
