import { useState } from "react";
import './style.css'

function isValidHttpUrl(string) {
  let url;

  try {
    url = new URL(string);
  } catch (_) {
    return false;
  }

  return url.protocol === "http:" || url.protocol === "https:";
}

export default function CommentForm({ url, site, path }) {
    const [error, setError] = useState(null);

    const handleSubmit = e => {
        e.preventDefault();

        let form = {
            name: e.target.elements.name.value,
            website: e.target.elements.user_website.value,
            message: e.target.elements.message.value,
            token: e.target.elements.token.value
        };

        if (form.name.length === 0) {
            setError("הזינו שם.");
            return;
        }
        if (form.message.length === 0) {
            setError("תגובה ריקה.");
            return;
        }
        if (form.token.length === 0) {
            setError("תשובה לשאלת סינון חסרה.");
            return;
        }
        if (form.website.length > 0 && !isValidHttpUrl(form.website)) {
            setError("אתר לא תקין. אולי שכחתם לציין את הפרוטוקול?");
            return;
        }

        fetch(url + '/api/' + site + '/' + path, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(form)
        })
          .then(response => {
              if (response.ok) {
                  window.location.reload();
              } else {
                  response.json().then((err) => { console.log(err); setError(err); });
              }
          })
          .catch(error => {
              console.log(error);
          });
    };

    return (
       <form onSubmit={handleSubmit} className="new-comment">
           <h4>כתיבת תגובה</h4>
           <div>
               <textarea className="new-comment-message" name="message" minLength="1" maxLength="1000" required="" placeholder="התגובה שלך" />
           </div>
           <div className="new-comment-user">
               <input className="new-comment-username" type="text" name="name" placeholder="שם" minLength="1" required="" />
               <input className="new-comment-user-website" type="url" name="user_website" placeholder="אתר" />
           </div>
           <div className="new-comment-div">
               <input className="new-comment-token" type="text" name="token" required="" minLength="1" placeholder="שאלת סינון" />
               <button className="new-comment-submit" type="submit" title="Add a new submission">הוספה</button>
           </div>
           <div className="error"><p>{error}</p></div>
       </form>
    )
}
