import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './Register.module.css';
import logo from '../assets/logos/PowerOn.png';
import agentDiagram from '../assets/logos/Frame 43.png';
import { useRegister, useMsalRegister } from '../hooks/useAuthentication';

interface RegisterFormData {
  username: string;
  password: string;
  confirmPassword: string;
  email: string;
  fullName: string;
}

function Register() {
  const navigate = useNavigate();
  const { register, error: registerError, isLoading } = useRegister();
  const { registerWithMsal, error: msalError, isLoading: msalLoading } = useMsalRegister();
  const [formData, setFormData] = useState<RegisterFormData>({
    username: '',
    password: '',
    confirmPassword: '',
    email: '',
    fullName: ''
  });
  const [validationError, setValidationError] = useState<string | null>(null);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
    setValidationError(null);
  };

  const validateForm = (): boolean => {
    if (!formData.username || !formData.password || !formData.confirmPassword || !formData.email || !formData.fullName) {
      setValidationError('Bitte füllen Sie alle Pflichtfelder aus.');
      return false;
    }

    if (formData.password !== formData.confirmPassword) {
      setValidationError('Die Passwörter stimmen nicht überein.');
      return false;
    }

    if (!formData.email.includes('@')) {
      setValidationError('Bitte geben Sie eine gültige E-Mail-Adresse ein.');
      return false;
    }

    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }

    try {
      const { confirmPassword, ...registrationData } = formData;
      await register(registrationData);
      navigate('/login', { 
        state: { 
          registered: true,
          message: 'Registration erfolgreich. Bitte melden Sie sich an.' 
        } 
      });
    } catch (err) {
      console.error('Registration failed:', err);
    }
  };

  const handleMsalRegister = async () => {
    try {
      await registerWithMsal();
      navigate('/login', {
        state: {
          registered: true,
          message: 'Microsoft Registration erfolgreich. Bitte melden Sie sich an.'
        }
      });
    } catch (err) {
      console.error('Microsoft registration failed:', err);
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.leftPanel}>
        <div className={styles.logo}>
          <img src={logo} alt="PowerOn Logo" onClick={() => navigate('/')} style={{ cursor: 'pointer' }} />
        </div>
        <div className={styles.registerBox}>
          <h1 className={styles.title}>Organisation registrieren</h1>
          
          {/* Microsoft Register Button */}
          <button
            type="button"
            className={`${styles.button} ${styles.msalButton}`}
            onClick={handleMsalRegister}
            disabled={msalLoading}
          >
            
            {msalLoading ? "Registrierung läuft..." : "Mit Microsoft registrieren"}
          </button>

          <div className={styles.divider}>
            <span>oder</span>
          </div>
          
          <form className={styles.registerForm} onSubmit={handleSubmit}>
            {(validationError || registerError || msalError) && (
              <div className={styles.error}>
                {validationError || registerError || msalError}
              </div>
            )}
            
            <div className={styles.inputGroup}>
              <label htmlFor="username">Benutzername *</label>
              <input
                id="username"
                type="text"
                name="username"
                value={formData.username}
                onChange={handleInputChange}
                className={styles.input}
                placeholder="Geben Sie Ihren Benutzernamen ein"
              />
            </div>

            <div className={styles.inputGroup}>
              <label htmlFor="password">Passwort *</label>
              <input
                id="password"
                type="password"
                name="password"
                value={formData.password}
                onChange={handleInputChange}
                className={styles.input}
                placeholder="Geben Sie Ihr Passwort ein"
              />
            </div>

            <div className={styles.inputGroup}>
              <label htmlFor="confirmPassword">Passwort bestätigen *</label>
              <input
                id="confirmPassword"
                type="password"
                name="confirmPassword"
                value={formData.confirmPassword}
                onChange={handleInputChange}
                className={styles.input}
                placeholder="Bestätigen Sie Ihr Passwort"
              />
            </div>

            <div className={styles.inputGroup}>
              <label htmlFor="email">E-Mail *</label>
              <input
                id="email"
                type="email"
                name="email"
                value={formData.email}
                onChange={handleInputChange}
                className={styles.input}
                placeholder="Geben Sie Ihre E-Mail-Adresse ein"
              />
            </div>

            <div className={styles.inputGroup}>
              <label htmlFor="fullName">Vollständiger Name *</label>
              <input
                id="fullName"
                type="text"
                name="fullName"
                value={formData.fullName}
                onChange={handleInputChange}
                className={styles.input}
                placeholder="Geben Sie Ihren vollständigen Namen ein"
              />
            </div>

            <button 
              type="submit"
              className={`${styles.button} ${styles.primaryButton}`}
              disabled={isLoading}
            >
              {isLoading ? "Registrierung läuft..." : "Registrieren"}
            </button>

            <div className={styles.loginLink}>
              <span>Bereits registriert?</span>
              <button 
                type="button"
                className={styles.textButton}
                onClick={() => navigate('/login')}
              >
                Jetzt anmelden
              </button>
            </div>
          </form>
        </div>
      </div>
      <div className={styles.rightPanel}>
        <div className={styles.rightContent}>
          <img src={agentDiagram} alt="Agent Diagram" />
        </div>
      </div>
    </div>
  );
}

export default Register;