"use client";

import { useState } from "react";
import { signOut } from "next-auth/react";

export function EmailForm({ hasPassword }: { hasPassword: boolean }) {
  const [newEmail, setNewEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setSuccess(false);
    setLoading(true);
    try {
      const res = await fetch("/api/profile/email", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ newEmail, password }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || "Une erreur est survenue.");
      } else {
        setSuccess(true);
        // Sign out so user logs back in with new email
        setTimeout(() => signOut({ redirectTo: "/auth/login" }), 2000);
      }
    } catch {
      setError("Une erreur est survenue.");
    } finally {
      setLoading(false);
    }
  };

  if (!hasPassword) {
    return (
      <p style={{ fontSize: 13, color: "#64748b", fontStyle: "italic" }}>
        Définissez d'abord un mot de passe ci-dessus.
      </p>
    );
  }

  return (
    <form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div>
        <label style={{ display: "block", fontSize: 13, fontWeight: 600, color: "#94a3b8", marginBottom: 6 }}>
          Nouvel email
        </label>
        <input
          type="email"
          value={newEmail}
          onChange={(e) => setNewEmail(e.target.value)}
          placeholder="nouveau@exemple.com"
          required
          style={{ fontSize: 14 }}
        />
      </div>

      <div>
        <label style={{ display: "block", fontSize: 13, fontWeight: 600, color: "#94a3b8", marginBottom: 6 }}>
          Confirmez votre mot de passe
        </label>
        <input
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder="Votre mot de passe actuel"
          required
          autoComplete="current-password"
          style={{ fontSize: 14 }}
        />
      </div>

      {error && (
        <p style={{ fontSize: 13, color: "#f87171", background: "rgba(239,68,68,0.1)", border: "1px solid rgba(239,68,68,0.3)", borderRadius: 6, padding: "10px 12px" }}>
          {error}
        </p>
      )}

      {success && (
        <p style={{ fontSize: 13, color: "#4ade80", background: "rgba(34,197,94,0.1)", border: "1px solid rgba(34,197,94,0.3)", borderRadius: 6, padding: "10px 12px" }}>
          ✓ Email mis à jour. Reconnexion en cours…
        </p>
      )}

      <button
        type="submit"
        disabled={loading || !newEmail || !password}
        className="btn btn-primary"
        style={{ justifyContent: "center", opacity: loading || !newEmail || !password ? 0.7 : 1, cursor: loading || !newEmail || !password ? "not-allowed" : "pointer" }}
      >
        {loading ? "Enregistrement…" : "Changer l'email"}
      </button>
    </form>
  );
}
