import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { createNewClient } from '../../services/billing_api';
import NotificationModal from '../../components/ui/NotificationModal';

export default function Register() {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');

  const [loading, setLoading] = useState(false);
  const [customAlert, setCustomAlert] = useState(null);
  const navigate = useNavigate();

  const handleRegister = async (e) => {
    e.preventDefault();
    setCustomAlert(null);

    const passwordPolicy = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/;
    if (!passwordPolicy.test(password)) {
      setCustomAlert({ type: 'error', title: 'Sécurité compromise', message: "Le mot de passe doit contenir 8 caractères min, une majuscule, une minuscule, un chiffre et un caractère spécial." });
      return;
    }
    if (password !== confirmPassword) {
      setCustomAlert({ type: 'error', title: 'Erreur de saisie', message: "Les clés d'accès ne correspondent pas." });
      return;
    }
    if (!/^[a-zA-Z0-9]{3,20}$/.test(username)) {
      setCustomAlert({ type: 'error', title: 'Identifiant invalide', message: "Le nom d'utilisateur doit contenir uniquement des lettres ou chiffres (entre 3 et 12 caractères)." });
      return;
    }

    setLoading(true);
    try {
      await createNewClient(email, firstName, lastName, password, confirmPassword, "individual", username);
      setCustomAlert({ type: 'success', title: 'PROVISIONNEMENT RÉUSSI', message: "Votre compte a été initialisé.\n\nVous pouvez maintenant vous connecter." });
    } catch (err) {
      setCustomAlert({ type: 'error', title: 'Échec du Déploiement', message: err.message || "Échec de l'initialisation." });
    } finally {
      setLoading(false);
    }
  };

  const handleCloseModal = () => {
    if (customAlert?.type === 'success') navigate('/login');
    else setCustomAlert(null);
  };

  return (
    <div className="flex justify-center mt-[5vh] px-5">
      <div className="w-full max-w-125 bg-[#242424] p-8 border-t-4 border-cyan-400 shadow-[0_10px_30px_rgba(0,0,0,0.5)]">
        <h2 className="text-white uppercase mb-1 text-2xl font-sans font-bold">
          Créer un accès réseau
        </h2>
        <p className="text-[#888] font-mono text-sm mb-6">
          [ INITIALISATION DU PROVISIONNEMENT ]
        </p>

        <form onSubmit={handleRegister} className="font-mono">
          <div className="flex gap-4">
            <div className="flex-1">
              <label className="block text-[#888] mb-1 text-xs tracking-widest uppercase">Prénom</label>
              <input type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)} required placeholder="John" className="w-full p-3 mb-4 bg-[#1A1A1A] text-cyan-400 border border-[#333] outline-none focus:border-cyan-400 transition-colors" />
            </div>
            <div className="flex-1">
              <label className="block text-[#888] mb-1 text-xs tracking-widest uppercase">Nom</label>
              <input type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} required placeholder="Doe" className="w-full p-3 mb-4 bg-[#1A1A1A] text-cyan-400 border border-[#333] outline-none focus:border-cyan-400 transition-colors" />
            </div>
          </div>

          <label className="block text-[#888] mb-1 text-xs tracking-widest uppercase">E-mail (Facturation)</label>
          <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required placeholder="john.doe@gise.be" className="w-full p-3 mb-4 bg-[#1A1A1A] text-cyan-400 border border-[#333] outline-none focus:border-cyan-400 transition-colors" />

          <label className="block text-[#888] mb-1 text-xs tracking-widest uppercase">Identifiant sécurisé (Cloud)</label>
          <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} required placeholder="ex: jdoe42" className="w-full p-3 mb-4 bg-[#1A1A1A] text-cyan-400 border border-[#333] outline-none focus:border-cyan-400 transition-colors" />

          <label className="block text-[#888] mb-1 text-xs tracking-widest uppercase">Clé d'accès unique</label>
          <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required placeholder="••••••••" className="w-full p-3 mb-4 bg-[#1A1A1A] text-cyan-400 border border-[#333] outline-none focus:border-cyan-400 transition-colors" />

          <label className="block text-[#888] mb-1 text-xs tracking-widest uppercase">Confirmer la clé</label>
          <input type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} required placeholder="••••••••" className="w-full p-3 mb-5 bg-[#1A1A1A] text-cyan-400 border border-[#333] outline-none focus:border-cyan-400 transition-colors" />

          <button type="submit" disabled={loading} className="w-full p-3 mt-2 font-bold uppercase tracking-widest transition-colors disabled:bg-[#333] disabled:text-[#888] disabled:cursor-not-allowed bg-cyan-400 hover:bg-cyan-300 text-black shadow-[0_0_15px_rgba(0,229,255,0.2)]">
            {loading ? 'DÉPLOIEMENT EN COURS...' : 'LANCER LE PROVISIONNEMENT'}
          </button>
        </form>

        <div className="mt-5 text-center text-sm font-mono text-[#888]">
          Déjà enregistré ?{' '}
          <Link to="/login" className="text-cyan-400 hover:text-cyan-300 transition-colors no-underline">
            Se connecter au terminal &gt;
          </Link>
        </div>
      </div>
      <NotificationModal notification={customAlert} onClose={handleCloseModal} />
    </div>
  );
}