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

function App() {
  const formSectionRef = useRef(null);
  const [names, setNames] = useState([""]);
  const [email, setEmail] = useState("");
  const [showManagement, setShowManagement] = useState(false);
  const [loginPassword, setLoginPassword] = useState("");
  const [isLoggedIn, setisLoggedIn] = useState(false);
  const [data, setData] = useState({
    time: "",
    date: "",
    price: "",
    food: false,
    endtime: "2026-03-27T17:30:00",
  });

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => {
      setisLoggedIn(user ? true : false)
    })
    const unsub1 = onSnapshot(doc(db, "time", "time"), (data) => {
      setData(data.data())
    })
    return () => {
      unsub()
      unsub1()
    };
  }, []);

  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 eintragen");
      return;
    }
    if(names.length === 0){
      alert("Bitte mindestens eine Person eintragen.")
      return;
    }
    for (let i = 0; i < names.length; i++) {
      if(names[i] === ""){
        alert("Bitte einen Name für Person " + (i+1) + " eintragen")
        return;
      }
    }
    // send data
    try {
      await addDoc(collection(db, "forms"), {
        email,
        names,
      })
      alert("Anmeldung gesendet.")
      window.location.reload(true)
    } catch (error) {
      console.error("Firestore Error:", error);
      alert("Fehler beim Senden der Anmeldung: " + error.message);
    }
  }

  const handleLogin = async (e) => {
    e.preventDefault();
    try {
      await signInWithEmailAndPassword(auth, "ex@luisk.de", loginPassword)
      setLoginPassword("")
    } catch (error) {
      if (error.code === 'auth/wrong-password' || error.code === 'auth/invalid-credential') {
        alert("Falsches Passwort!");
      } else if (error.code === 'auth/user-not-found') {
        alert("Benutzer nicht gefunden!");
      } else {
        alert("Fehler beim Login. Bitte versuchen Sie es später erneut.");
        console.error(error);
      }
      setLoginPassword("");
    }
  }

  const createPersonFields = () => {
    return names.map((name, i) => (
      <div key={i} style={{ display: 'flex', gap: '10px', marginBottom: '10px', alignItems: 'center' }}>
        <input 
          type="text" 
          placeholder={"Name " + (i+1) + ". Person"} 
          value={name} 
          onChange={(e) => {
            let prev = [...names]
            prev[i] = e.target.value
            setNames(prev)
          }} 
        />
        <button
          type="button"
          onClick={() => {
            setNames(names.filter((_, index) => index !== i))
          }}
          style={{ background: '#ff4444', color: 'white', border: 'none', padding: '5px 10px', cursor: 'pointer', borderRadius: '4px' }}
        >
          🗑️
        </button>
      </div>
    ))
  } 

  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={() => setShowManagement(false)} style={{background:'#888',marginTop:'10px'}}>Abbrechen</button>
            </form>
          ) : <Admin close={() => setShowManagement(false)} />}
        </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">{data.time}</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">{data.date}</span>
              </div>
              <div className="fact-row">
                <span className="fact-label">Eintrittspreis:</span>
                <span className="fact-value">{data.price}€</span>
              </div>
              <div className="fact-row">
                <span className="fact-label">Anmeldung spätestens bis:</span>
                <span className="fact-value">{ new Date(data.endtime).toLocaleDateString() } (online oder vor Ort)</span>
              </div>
              <br />
              <div className="fact-row">
                {/* <span className='fact-label'></span> */}
                <span className="fact-value">Ausschließlich für Schüler, Lehrer und Familienmitglieder.</span>
              </div>
              { data.food && <div className="fact-row">
                <span className='fact-value'>Für Verpflegung ist gesorgt.</span>
              </div> }
            </div>
            <button onClick={scrollToForm}>Jetzt Anmelden</button>
          </div>
          <div id="form-section" ref={formSectionRef}>
            { new Date() > new Date(data.endtime) ? <h1 style={{ color: 'white', background: 'red', padding: '20px' }}>Die Anmeldefrist ist leider schon abgelaufen</h1> : 
              <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>Namen</label>
                <button type='button' onClick={() => setNames([...names, ""]) }>Neue Person hinzufügen</button>
                { createPersonFields() }
                <br />
                <button type="submit" onClick={submit}>Anmelden</button>
              </form>
            }
          </div>
        </>
      )}
      <footer>
        <p>
          <button type="button" onClick={() => setShowManagement(!showManagement)} style={{ marginRight: '20px', cursor: 'pointer' }}>Verwaltung { showManagement ? "schließen" : "öffnen" }</button>
          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;