<script>
 import { createEventDispatcher } from 'svelte';

 import {
     Alert,
     Badge,
     Button,
     Card,
     Col,
     Container,
     Icon,
     Row,
 } from '@sveltestrap/sveltestrap';

 import { settings } from '$lib/stores/settings.js';

 import RegistrationRowMember from './RegistrationRowMember.svelte';

 const dispatch = createEventDispatcher();

 export let value = {members:[{}]};

 function validateTeamName() {
     if (typeof value.members !== 'Array') {
         value.members = [{ }];
     } else if (value.members.length <= 0) {
         value.members.push({ });
     }
     partR = true;
 }

 function AddMember() {
     value.members.push({ });
     value = value;
 }

 function RemoveMember(mid) {
     console.log(mid);
 }

 function submit(event) {
     if (!partR) {
         validateTeamName();
     } else {
         // Ensure jTeam, defined by RegistrationFormJoinTeam is not defined
         delete value.jTeam;

         dispatch('submit', event);
     }
 }

 const max_team_members = 3;
 let jTeam = false;
 export let partR = false;
 let message = "";
 let messageClass = "danger";
</script>

<form on:submit|preventDefault={submit}>
    <Row>
        <label for="teamName" class="col col-form-label">Nom d'équipe</label>
        <div class="col-sm-10">
	    <div class="input-group">
                <!-- svelte-ignore a11y-autofocus -->
	        <input type="text" class="form-control" id="teamName" bind:value={value.teamName} placeholder="" autofocus required>
	        <Button color="info" type="button" on:click={validateTeamName} disabled={jTeam}>Valider</Button>
	        <div class="invalid-feedback">
	            Veuillez indiquer un nom d'équipe valide.
	        </div>
	    </div>
        </div>
    </Row>

    {#if partR}
        <h4 class="mt-4">
            {#if !$settings.canJoinTeam}
	        Membres d'équipe
	        <Button
                    color="success"
                    disabled={value.members.length >= max_team_members}
                    size="sm"
                    type="button"
                    on:click={AddMember}
                >
                    <Icon name="person-plus-fill" />
                    Ajouter un membre
	        </Button>
            {:else}
	        Chef d'équipe
            {/if}
        </h4>
        {#if message}
            <p class={messageClass}>{message}</p>
        {/if}

        {#each value.members as member, mid}
            <RegistrationRowMember
                canDelete={!$settings.canJoinTeam && value.members.length > 1}
                bind:member={member}
                on:delete={RemoveMember}
            />
        {/each}

        <Row>
            <Col sm={{ size: 9, offset: 3 }} md={{ size: 8, offset: 4 }}>
            <Button color="info" class="mt-4" type="submit" disabled={jTeam}>
	        C'est parti&nbsp;!
                <Icon name="chevron-right" />
            </Button>
            </Col>
        </Row>
    {/if}
</form>
