import "../style/home/home.css"
import { useNavigate } from "react-router-dom"
import { useEffect, useState } from "react"
import { User } from "../model/User.ts"
import { useAppFetcher } from "../App.tsx"

interface Tactic {
    id: number
    name: string
    creationDate: number
}

interface Team {
    id: number
    name: string
    picture: string
    main_color: string
    second_color: string
}

export default function HomePage() {
    type UserDataResponse = { user?: User; tactics: Tactic[]; teams: Team[] }
    const [{ tactics, teams }, setInfo] = useState<UserDataResponse>({
        tactics: [],
        teams: [],
    })

    const navigate = useNavigate()
    const fetcher = useAppFetcher()

    useEffect(() => {
        async function initUserData() {
            const response = await fetcher.fetchAPIGet("user-data")
            if (response.status == 401) {
                navigate("/login")
                return // if unauthorized
            }
            setInfo(await response.json())
        }

        initUserData()
    }, [fetcher, navigate])

    tactics!.sort((a, b) => b.creationDate - a.creationDate)

    const lastTactics = tactics.slice(0, 5)
    return (
        <Home teams={teams!} allTactics={tactics!} lastTactics={lastTactics} />
    )
}

function Home({
    lastTactics,
    allTactics,
    teams,
}: {
    lastTactics: Tactic[]
    allTactics: Tactic[]
    teams: Team[]
}) {
    return (
        <div id="main">
            <Body
                lastTactics={lastTactics}
                allTactics={allTactics}
                teams={teams}
            />
        </div>
    )
}

function Body({
    lastTactics,
    allTactics,
    teams,
}: {
    lastTactics: Tactic[]
    allTactics: Tactic[]
    teams: Team[]
}) {
    const widthPersonalSpace = 78
    const widthSideMenu = 100 - widthPersonalSpace
    return (
        <div id="body">
            <PersonalSpace width={widthPersonalSpace} allTactics={allTactics} />
            <SideMenu
                width={widthSideMenu}
                lastTactics={lastTactics}
                teams={teams}
            />
        </div>
    )
}

function SideMenu({
    width,
    lastTactics,
    teams,
}: {
    width: number
    lastTactics: Tactic[]
    teams: Team[]
}) {
    return (
        <div
            id="side-menu"
            style={{
                width: width + "%",
            }}>
            <div id="side-menu-content">
                <Team teams={teams} />
                <Tactic lastTactics={lastTactics} />
            </div>
        </div>
    )
}

function PersonalSpace({
    width,
    allTactics,
}: {
    width: number
    allTactics: Tactic[]
}) {
    return (
        <div
            id="personal-space"
            style={{
                width: width + "%",
            }}>
            <TitlePersonalSpace />
            <BodyPersonalSpace allTactics={allTactics} />
        </div>
    )
}

function TitlePersonalSpace() {
    return (
        <div id="title-personal-space">
            <h2>Espace Personnel</h2>
        </div>
    )
}

function TableData({ allTactics }: { allTactics: Tactic[] }) {
    const nbRow = Math.floor(allTactics.length / 3) + 1
    const listTactic = Array(nbRow)
    for (let i = 0; i < nbRow; i++) {
        listTactic[i] = Array(0)
    }
    let i = 0
    let j = 0
    allTactics.forEach((tactic) => {
        listTactic[i].push(tactic)
        j++
        if (j === 3) {
            i++
            j = 0
        }
    })

    const navigate = useNavigate()

    i = 0
    while (i < nbRow) {
        listTactic[i] = listTactic[i].map((tactic: Tactic) => (
            <td
                key={tactic.id}
                className="data"
                onClick={() => {
                    navigate("/tactic/" + tactic.id + "/edit")
                }}>
                {truncateString(tactic.name, 25)}
            </td>
        ))
        i++
    }
    if (nbRow == 1) {
        if (listTactic[0].length < 3) {
            for (let i = 0; i <= 3 - listTactic[0].length; i++) {
                listTactic[0].push(<td key={"tdNone" + i}></td>)
            }
        }
    }

    return listTactic.map((tactic, rowIndex) => (
        <tr key={rowIndex + "row"}>{tactic}</tr>
    ))
}

function BodyPersonalSpace({ allTactics }: { allTactics: Tactic[] }) {
    return (
        <div id="body-personal-space">
            {allTactics.length == 0 ? (
                <p>Aucune tactique créée !</p>
            ) : (
                <table>
                    <tbody key="tbody">
                        <TableData allTactics={allTactics} />
                    </tbody>
                </table>
            )}
        </div>
    )
}

function Team({ teams }: { teams: Team[] }) {
    const navigate = useNavigate()
    return (
        <div id="teams">
            <div className="titre-side-menu">
                <h2 className="title">Mes équipes</h2>
                <button className="new" onClick={() => navigate("/team/new")}>
                    +
                </button>
            </div>
            <SetButtonTeam teams={teams} />
        </div>
    )
}

function Tactic({ lastTactics }: { lastTactics: Tactic[] }) {
    const navigate = useNavigate()

    return (
        <div id="tactic">
            <div className="titre-side-menu">
                <h2 className="title">Mes dernières tactiques</h2>
                <button
                    className="new"
                    id="create-tactic"
                    onClick={() => navigate("/tactic/new")}>
                    +
                </button>
            </div>
            <SetButtonTactic tactics={lastTactics} />
        </div>
    )
}

function SetButtonTactic({ tactics }: { tactics: Tactic[] }) {
    const lastTactics = tactics.map((tactic) => (
        <ButtonLastTactic key={tactic.id} tactic={tactic} />
    ))
    return <div className="set-button">{lastTactics}</div>
}

function SetButtonTeam({ teams }: { teams: Team[] }) {
    const listTeam = teams.map((team) => (
        <ButtonTeam key={team.id} team={team} />
    ))
    return <div className="set-button">{listTeam}</div>
}

function ButtonTeam({ team }: { team: Team }) {
    const name = truncateString(team.name, 20)
    const navigate = useNavigate()

    return (
        <div>
            <div
                id={"button-team" + team.id}
                className="button-side-menu data"
                onClick={() => {
                    navigate("/team/" + team.id)
                }}>
                {name}
            </div>
        </div>
    )
}

function ButtonLastTactic({ tactic }: { tactic: Tactic }) {
    const name = truncateString(tactic.name, 20)
    const navigate = useNavigate()

    return (
        <div
            id={"button" + tactic.id}
            className="button-side-menu data"
            onClick={() => {
                navigate("/tactic/" + tactic.id + "/edit")
            }}>
            {name}
        </div>
    )
}

function truncateString(name: string, limit: number): string {
    if (name.length > limit) {
        name = name.substring(0, limit) + "..."
    }
    return name
}
