<script>
  import { CardHeader, CardTitle, Button, Card, Input, Form, CardBody, FormGroup } from '@sveltestrap/sveltestrap';
  import { navigate } from 'svelte-routing';
  
  let email = ""
  let contraseña = ""
  let errorMessage = ""
  let showAlert = false; 
  
  async function submitForm(event) {
    event.preventDefault();
    
    const data = {email, contraseña};
    try{
      const response = await fetch("http://127.0.0.1:5007/api/login",{ 
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });

      if (!response.ok){
       const errorData = await response.json()
       errorMessage = errorData.message;
       showAlert = true;
       return;
      }

      const ret = await response.json();
      localStorage.clear();
      localStorage.setItem('token', ret.token);
      localStorage.setItem('email', ret.email);
      //setTimeout(() => console.log("50ms") ,50);
      navigate(ret.redirect);
    } catch (e) {
    }
   
  }

</script>

<Card class="position-sticky top-50 start-50 translate-middle-x" style="width: 18rem; height: auto;" theme="auto" color="dark" outline>
  <CardHeader>
    <CardTitle>Iniciar Sesión</CardTitle>
  </CardHeader>
  <CardBody>
    <Form on:submit={submitForm}>
      <FormGroup floating label="Email">
        <Input type="email" placeholder="ejemplo@mail.com" bind:value={email}/>
      </FormGroup>
      <FormGroup floating label="Contraseña">
        <Input type="password" placeholder="*********" bind:value={contraseña}/>
      </FormGroup>     
      <FormGroup>
        <Button color="primary" type="submit">Ingresar</Button>
      </FormGroup>     
    </Form>
{#if errorMessage}
    <div class='alert alert-warning alert-dismissible fade show' role='alert'>
      <strong>{errorMessage}</strong> 
      <button type="button" class="btn-close close" aria-label="Close" data-dismiss="alert"></button>
    </div>
{/if}
  </CardBody>
</Card>
