import logoSrc from "./logo_p.svg";
import React, { useState } from "react";
import firebase from "firebase/app";
import TextField from "@mui/material/TextField";
import { Container, Stack } from "@mui/system";
import { Button, Typography } from "@mui/material";
import { useForm } from "react-hook-form";
import Countdown from "./Countdown";
import ImageUpload from "./ImageUpload";

export const MyForm = () => {
  const [mandato, cambiaMandato] = useState(false);
  const [immagineURL, cambiaimmagineURL] = useState(null);
  const { register, handleSubmit } = useForm();
  const onSubmit = ({ testo, autore }) => {
    cambiaMandato(true);
    var postListRef = firebase.database().ref("messaggi");
    var newPostRef = postListRef.push();
    const update = {
      id: newPostRef.key,
      autore,
      testo,
      timestamp: firebase.database.ServerValue.TIMESTAMP,
      approvato: true,
    };
    if (immagineURL) update.immagineURL = immagineURL;
    newPostRef.set(update);
  };

  const onImageURLSet = (url) => {
    cambiaimmagineURL(url);
  };

  if (mandato) {
    return (
      <Stack>
        <div>mandato e mo aspetti</div>
        <Countdown onComplete={() => cambiaMandato(false)} duration={5} />
      </Stack>
    );
  }
  return (
    <Container maxWidth="sm" style={{ marginTop: 20 }}>
      <div style={{ textAlign: "center" }}>
        <img
          src={logoSrc}
          style={{
            width: 200,
          }}
        />
        <Typography
          variant="h5"
          style={{ marginBottom: 40, fontFamily: "Lineatura" }}
        >
          Manda un messaggio!
        </Typography>
      </div>
      <form onSubmit={handleSubmit(onSubmit)}>
        <Stack spacing={2}>
          <TextField
            multiline
            rows={4}
            {...register("testo", { required: true, maxLength: 20 })}
            id="outlined-basic"
            label="messaggio"
            variant="outlined"
          />
          <TextField
            {...register("autore", { pattern: /^[A-Za-z]+$/i })}
            id="outlined-basic"
            label="da"
            variant="outlined"
          />
          <ImageUpload onImageURLSet={onImageURLSet} />
          <Button
            className="okbutton"
            type="submit"
            style={{
              padding: "30px 0px",
              fontSize: 20,
              fontFamily: "Lineatura",
            }}
            variant="contained"
          >
            ok
          </Button>
        </Stack>
      </form>
    </Container>
  );
};
