import { useRef } from 'react';
import App from '../components/App'

import { collection, query, orderBy } from '@firebase/firestore';
import { useFirestore, useFirestoreCollectionData } from 'reactfire';

export default function Home() {
  const firestore = useFirestore();
  const questionnaireCollection = collection(firestore, 'questionnaire');
  const questionnaireQuery = query(questionnaireCollection, orderBy('created', 'desc'));

  const { status, data: questionnaire } = useFirestoreCollectionData(questionnaireQuery, {
    idField: 'id', // this field will be added to the object created from each document
  });

  const Q1Ref = useRef();

  async function handleSubmit(event) {
    event.preventDefault();

    let body = JSON.stringify({
      Q1: Q1Ref.current.value,
    });
    try {
      let r = await fetch("/api/addQuestionnaire", {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': body.length.toString(),
        },
        body: body,
      });
      let data = await r.json();
      console.log(data);
    }
    catch (e) {
      console.error(e);
    }
    console.log(Q1Ref.current.value);
  }

  return (
    <App>
      <div className="artboard phone-1 rounded-lg border-0 flex flex-col p-2 gap-4">
        <form className="form-control w-full max-w-xs gap-2" onSubmit={handleSubmit}>
          <label className="label">
            <span className="label-text">你最喜歡的科幻/奇幻作品是哪一個？</span>
            {/* <span class="label-text-alt">Alt label</span> */}
          </label>
          {/* <select className="select select-bordered" value="Pick one" onChange={handleChange}> */}
          <select className="select select-bordered" ref={Q1Ref}>
            <option disabled selected>Pick one</option>
            <option>Star Wars</option>
            <option>Harry Potter</option>
            <option>Lord of the Rings</option>
            <option>Planet of the Apes</option>
            <option>Star Trek</option>
          </select>
          <input className="btn" type="submit" value="Submit" />
          {/* <label class="label">
            <span class="label-text-alt">Alt label</span>
            <span class="label-text-alt">Alt label</span>
          </label> */}
        </form>
        {/* <button className="btn" onClick={() => console.log("test")}>Button</button> */}
        {
          status == 'success' && questionnaire.map(q => (
            <div key={q.id} className=' '>{q.Q1}</div>
          ))
        }
      </div>
    </App>
  )
}
