import { useEffect, useRef, useState } from 'react';
import './App.css';
import { addDoc, collection, doc, getDoc, onSnapshot } from 'firebase/firestore';
import { db } from './firebase';

function App() {
  const radioGroupEntries = [1, 2, 3, 4]
  const formSectionRef = useRef(null);
  const [customNumber, setCustomNumber] = useState(false);
  const [number, setNumber] = useState(null)
  const [email, setEmail] = useState("");
  const [showManagement, setShowManagement] = useState(false);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [loginPassword, setLoginPassword] = useState("");
  const [data, setData] = useState([]);

  useEffect(() => {
    let unsub = onSnapshot(collection(db, "forms"), (snapshot) => {
      let data = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
      for(let i = 0; i < data.length; i++){
        let element = data[i]
        if(element.id === "3GQrSzfPaZHZWleu6sq7") data.splice(i, 1)
      }
      setData(data)
    })
    return () => {
      unsub();
    };
  }, []);

  const getNumberOfUsers = () => {
    let number = 0
    for(let user of data){
      number += user.number
    }
    return number;
  }

  const scrollToForm = () => {
    const formSection = formSectionRef.current;
    formSection.classList.add('visible', 'bounce'); // Füge Bounce-Klasse hinzu
    setTimeout(() => {
      formSection.scrollIntoView({ behavior: 'smooth' });
      formSection.classList.remove('bounce'); // Entferne Bounce-Klasse nach der Animation
    }, 190); // Wartezeit für die Bounce-Animation
  };

  const emailIsValid = (email1) => {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email1)
  }
  
  const submit = async (e) => {
    e.preventDefault(); // Verhindert das Standardverhalten des Formulars
    if (!emailIsValid(email)){
      alert("Bitte eine gültige E-Mailadresse eintrgen");
      return;
    }
    if(!number){
      alert("Bitte angeben wie viele Personen mitkommen");
      return;
    }
    // send data
    try {
      addDoc(collection(db, "forms"), {
        email: email,
        number: number
      })
    } catch (error) {
      alert("Fehler beim Senden der Anmeldung. Bitte versuche es später erneut.");
      console.error(error);
    }
    alert("Anmeldung gesendet.")
    setEmail("")
    setCustomNumber(false)
    setNumber(null)
  }

  const displayManagement = () => {
    setShowManagement(true);
  }
  const hideManagement = () => {
    setShowManagement(false);
    setIsLoggedIn(false);
    setLoginPassword("");
  }

  const handleLogin = async (e) => {
    e.preventDefault();
    let pw = await getDoc(doc(db, "forms",  "3GQrSzfPaZHZWleu6sq7"))
    let pw2 = pw.data()
    if (loginPassword === pw2.pw) {
      setIsLoggedIn(true);
      setLoginPassword("");
    } else {
      alert("Falsches Passwort!");
    }
  }

  return (
    <div className="App">
      {showManagement ? (
        <div id="management-section">
          {!isLoggedIn ? (
            <form onSubmit={handleLogin} className="login-form">
              <h2>Verwaltung Login</h2>
              <input
                type="password"
                placeholder="Passwort"
                value={loginPassword}
                onChange={e => setLoginPassword(e.target.value)}
                autoFocus
              />
              <button type="submit">Login</button>
              <button type="button" onClick={hideManagement} style={{background:'#888',marginTop:'10px'}}>Abbrechen</button>
            </form>
          ) : (
            <>
              <h2>Verwaltung</h2>
              <button onClick={hideManagement}>Abmelden & Zurück</button>
              {/* Gesamtanzahl Personen */}
              <div className="gesamtanzahl">
                Gesamtanzahl Personen: <b>{ getNumberOfUsers() }</b>
              </div>
              {/* Tabelle mit Dummy-Daten */}
              <table className="management-table">
                <thead>
                  <tr>
                    <th>E-Mail</th>
                    <th>Anzahl Personen</th>
                  </tr>
                </thead>
                <tbody>
                  { data.map(user => (
                    <tr key={user.id}>
                      <td>{ user.email }</td>
                      <td>{ user.number }</td>
                    </tr>
                  )) }
                </tbody>
              </table>
            </>
          )}
        </div>
      ) : (
        <>
          <div id="intro">
            <h1>Willkommen zum Skatabend des Skat-Profils</h1>
            <div className="facts">
              <div className="fact-row">
                <span className="fact-label">Zeit:</span>
                <span className="fact-value">18:00</span>
              </div>
              <div className="fact-row">
                <span className="fact-label">Ort:</span>
                <span className="fact-value">Samuel-von-Pufendorf-Gymnasium in Flöha</span>
              </div>
              <div className="fact-row">
                <span className="fact-label">Datum:</span>
                <span className="fact-value">25.06.2025</span>
              </div>
            </div>
            <button onClick={scrollToForm}>Jetzt Anmelden</button>
          </div>
          <div id="form-section" ref={formSectionRef}>
            <form>
              <label>E-Mail:</label>
              <input type="email" name="email" placeholder="Deine E-Mail-Adresse" onChange={(e => setEmail(e.target.value))} value={email}/>
              <br />
              <label>Anzahl der Personen</label>
                <div className="radio-group">
                  { radioGroupEntries.map((entry) => <label key={entry} style={ number === entry && !customNumber ? { backgroundColor: "rgba(0, 128, 0, 0.7)" } : null }>
                    <input
                       type="radio" 
                       name="number"
                       onChange={() => { setNumber(entry); setCustomNumber(false) }}
                      />
                    { entry } Person{ entry > 1 ? "en" : null }
                  </label> ) }
                  <label style={ customNumber ? { backgroundColor: "rgba(0, 128, 0, 0.7)" } : null }>
                    <input
                       type="radio" 
                       name="number"
                       onChange={() => setCustomNumber(true)}
                      />
                    Andere Nummer
                  </label>
                </div>
              {customNumber ? (
                <input
                  type="number"
                  name="customNumber"
                  placeholder="Anzahl der Personen"
                  min={1}
                  onChange={(e) => setNumber(parseInt(e.target.value))}
                  value={number}
                />
              ) : null}
              <br />
              <button type="submit" onClick={submit}>Anmelden</button>
            </form>
          </div>
        </>
      )}
      <footer>
        <p>
          <a onClick={displayManagement} style={{ marginRight: '20px', cursor: 'pointer' }}>Verwaltung öffnen</a>
          Bildquelle Hintergrund: <a href="https://store-images.s-microsoft.com/image/apps.42739.13510798887965433.cf25521d-d390-432c-8007-cbc0aa3ebe97.53ed75d0-4a6a-4c11-a3ae-fd528ef6444a?h=1280" target="_blank" rel="noopener noreferrer">hier klicken</a>
        </p>
      </footer>
    </div>
  );
}

export default App;