import {FormEvent, useState} from "react"
import { fetchAPI } from "../Fetcher.ts"
import { Failure } from "../api/failure.ts"
import "../style/form.css"
// @ts-ignore
import { useNavigate } from "react-router-dom"
import {getSession, saveSession} from "../api/session.ts";
export default function CreateTeamPage() {

    const [errors, setErrors] = useState<Failure[]>([])

    const navigate = useNavigate()

    async function handleSubmit(e : FormEvent){
        e.preventDefault()

        const { name, mainColor,secondColor,picture } = Object.fromEntries(
            new FormData(e.target as HTMLFormElement),
        )

         const response = await fetchAPI(
             "teams",
             {name,mainColor,secondColor,picture},
             "POST"
         )

        if(response.ok){
            const session = getSession()
            const teamId = await response.json()
            saveSession({
                ...session,
                auth: session.auth,
                urlTarget: "/team/"+teamId+"/members",
            })
            navigate(session.urlTarget)
            return
        }

        try {
            const failures = await response.json()
            setErrors(
                Object.entries<string[]>(failures).map(([type, messages]) => ({
                    type,
                    messages,
                })),
            )
        } catch (e) {
            setErrors([
                {
                    type: "internal error",
                    messages: ["an internal error occurred."],
                },
            ])
        }

    }

    return (
        <div className="container">
            <h2>Créer une équipe</h2>

            {errors.map(({ type, messages }) =>
                messages.map((message) => (
                    <p key={type} style={{ color: "red" }}>
                        {type} : {message}
                    </p>
                )),
            )}

            <form onSubmit={handleSubmit}>
                <div className="form-group">
                    <label htmlFor="name">Nom de l'équipe :</label>
                    <input
                        className="text-input"
                        type="text"
                        id="email"
                        name="email"
                        required
                    />
                    <label htmlFor="picture">Logo :</label>
                    <input
                        className="text-input"
                        type="text"
                        id="picture"
                        name="picture"
                        required
                    />
                    <label htmlFor="mainColor">Couleur principale :</label>
                    <input
                        className="color-input"
                        type="color"
                        id="main_color"
                        name="main_color"
                        value="#ffffff"
                        required
                    />
                    <label htmlFor="secondColor">Couleur secondaire :</label>
                    <input
                        className="color-input"
                        type="color"
                        id="second_color"
                        name="second_color"
                        required
                    />
                    <div id="buttons">
                        <input
                            className="button"
                            type="submit"
                            value="Confirmer"
                        />
                    </div>
                </div>
            </form>

        </div>


    )
}
