import React, { useState,useEffect } from "react";
import "./App.css";
import { Redirect} from "react-router-dom";
import update from "react-addons-update";

//loading spinner
import Spinner from "./spinner"


//options for yes/no answers
const optionsYes = [
  {
    label: "Ano",
    value: "1",
  },
  {
    label: "Spíše ano",
    value: "2",
  },
  {
    label: "Nevím",
    value: "3",
  },
  {
    label: "Spíše ne",
    value: "4",
  },
  {
    label: "Ne",
    value: "5",
  },
];

//options for often/none answers
const optionsOften = [
  {
    label: "Často",
    value: "1",
  },
  {
    label: "Občas",
    value: "2",
  },
  {
    label: "Nevím",
    value: "3",
  },
  {
    label: "Zřídka",
    value: "4",
  },
  {
    label: "Vůbec",
    value: "5",
  },
];
//options for memory
const optionsMem=[
  {
    label:"Pro náročné použití",
    value:"1",
  },
  {
    label:"Pro běžné použití",
    value:"2",
  },
  {
    label:"Nevím",
    value:"3",
  },
  {
    label:"Pro základní použití",
    value:"4",
  },
];

//options for phone answers
const optionsPhone = [
  {
    label: "Xiaomi",
    value: "Xiaomi",
  },
  {
    label: "Apple",
    value: "iPhone",
  },
  {
    label: "Samsung",
    value: "Samsung",
  },
  {
    label: "Realme",
    value: "Realme",
  },
  {
    label: "Motorola",
    value: "Motorola",
  },
  {
    label: "Lenovo",
    value: "Lenovo",
  },
  {
    label: "OnePlus",
    value: "OnePlus",
  },
  {
    label: "Nemám preference",
    value: "nezalezi",
  },
];

function Questions() {
  

  const answersDefault=[
    {
      value:'3',
    },
    {
      value:'3',
    },
    {
      value:'3',
    },
    {
      value:'3',
    },
    {
      value:'3',
    },
    {
      value:'3',
    },
    {
      value:'3',
    },
    {
      value:'3',
    },
    {
      value:'nezalezi'
    },
  ];
  const [answers,setAnswers]=useState(JSON.parse(localStorage.getItem('odpovedi'))|| answersDefault)

 const [data,setData]=useState([]);
 useEffect(() => {
   localStorage.setItem('odpovedi',JSON.stringify(answers));
 })

let mockphone=[];
const [loading,setLoading]=useState(false);
const [hasLoaded,setHasLoaded]=useState(false);
  function handleChange(e, number) {
    /**
     * function sets coresponding answer according to its numbers 
     * e - event 
     * number- number of question that was answered
     */
    console.log("moznost vybrana");
    console.log("otazka cislo %d", number);
    const value = e.target.value;
    console.log(value);
    setAnswers(update(answers, { [number]: { $set: { value } } }));
    console.log(answers);
  }

  async function handleSubmit() {
    /**
     * after clicking function sends data to backend a recieve back filtered phones
     */
    //setting loading to true to display loading spinner
    setLoading(true);
    console.log("odesilam");
     await fetch("/questions", {
      method: "POST",
      headers: {
        Content_Type: "application/json",
      },
      body: JSON.stringify(answers)
    }).then(response=>{if (response.ok) {
      console.log("data odeslana");
      const resjson=response.json();
      console.log("resjson");
      console.log(resjson);
      return resjson;
    } else {
      console.log("chyba pri odesilani dat");
    }}).then((datas)=>{setData(datas);return mockphone=datas;})
    // setting loading back to false so loading spinner disapppear 
    setLoading(false);
    //setting hasloaded to true so it redirect to result page 
    setHasLoaded(true);
  }
//function for clearing form
function handleClearForm() {
  setAnswers(answersDefault);
  window.location.reload();
}
//print answers
console.log(answers);

  return (
    <div className="App">
      <header>
        <h1>Průvodce výběrem mobilního telefonu</h1>
      </header>
      <form className="form">
        <div>
          <h3>Sledujete na telefonu videa?</h3>
        </div>
        <div>
          <select
            onChange={(evt) => handleChange(evt, 0)}
            //defaultValue={optionsYes[2].value}
            defaultValue={answers[0].value}
            className="questions-select"
          >
            {optionsYes.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </div>
      </form>
      <form className="form">
        <h3>Hrajete na telefonu hry?</h3>
        <select
          onChange={(evt) => handleChange(evt, 1)}
          //defaultValue={optionsYes[2].value}
          defaultValue={answers[1].value}
          className="questions-select"
        >
          {optionsOften.map((option) => (
            <option key={option.value} value={option.value} >
              {option.label}
            </option>
          ))}
        </select>
      </form>
      <form className="form">
        <h3>Budete používat telefon jako náhradu fotoaparátu?</h3>
        <select
          onChange={(evt) => handleChange(evt, 2)}
          //defaultValue={optionsYes[2].value}
          defaultValue={answers[2].value}
          className="questions-select"
        >
          {optionsYes.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      </form>
      <form className="form">
        <h3>Budete používat telefon při sportu?</h3>
        <select
          onChange={(evt) => handleChange(evt, 3)}
          //defaultValue={optionsYes[2].value}
          defaultValue={answers[3].value}
          className="questions-select"
        >
          {optionsYes.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      </form>
      <form className="form">
        <h3>Je pro Vás důležitá výdrž baterie?</h3>
        <select
          onChange={(evt) => handleChange(evt, 4)}
          //defaultValue={optionsYes[2].value}
          defaultValue={answers[4].value}
          className="questions-select"
        >
          {optionsYes.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      </form>
      <form className="form">
        <h3>Využíváte více SIM karet?</h3>
        <select
          onChange={(evt) => handleChange(evt, 5)}
          //defaultValue={optionsYes[2].value}
          defaultValue={answers[5].value}
          className="questions-select"
        >
          {optionsYes.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      </form>
      <form className="form">
        <h3>Jakou vyžadujete velikost paměti telefonu?</h3>
        <select
          onChange={(evt) => handleChange(evt, 6)}
          //defaultValue={optionsMem[2].value}
          defaultValue={answers[6].value}
          className="questions-select"
        >
          {optionsMem.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      </form>
      <form className="form">
        <div>
          <h3>Požadujete, aby byl telefon voděodolný?</h3>
        </div>
        <select
          onChange={(evt) => handleChange(evt, 7)}
          //defaultValue={optionsYes[2].value}
          defaultValue={answers[7].value}
          className="questions-select"
        >
          {optionsYes.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      </form>
      <form className="form">
        <h3>Preferujete konkrétní značku?</h3>
        <select
          onChange={(evt) => handleChange(evt, 8)}
          //defaultValue={optionsPhone[7].value}
          defaultValue={answers[8].value}
          className="questions-select"
        >
          {optionsPhone.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      </form>
      <div className="clearformbutton-container">
        {/*button for clearing form*/}
        <button onClick={handleClearForm} className="clearformbutton">Vyčistit formulář</button>
      </div>
      {/*submit button*/}
      <div className="button-container">
        <button onClick={handleSubmit} className="submit-button" type="submit">
          {/*<Link className="link-button" to={{pathname:"/results", state: data }}>*/}
            Odeslat
          {/*</Link>*/}
        </button>
      </div>
      {/*(loading)?( 
        <div>
          <div className="products">
           {/*<Results data={data}/>}
          <Redirect to={{pathname:"/results",data:data,znacka:answers[8]}} />
          </div>
        </div>
      ):(<Spinner />)*/}
      {
        loading &&
        <Spinner />
      }
      {
        hasLoaded &&
          <Redirect to={{pathname:"/results",data:data,znacka:answers[8]}} />
        
      }
    </div>
  );
}

export default Questions;
