"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { User, Mail, Lock, Eye, EyeOff } from "lucide-react";
import toast, { Toaster } from "react-hot-toast";
import styles from "../login/login.module.css";

export default function RegisterPage() {
  const router = useRouter();
  const [form, setForm] = useState({
    firstName: "", lastName: "",
    email: "", password: "", confirmPassword: "",
  });
  const [showPass, setShowPass]       = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [loading, setLoading]         = useState(false);
  const [error, setError]             = useState("");
  const [success, setSuccess]         = useState(false);

  const set = (field: string, value: string) =>
    setForm((prev) => ({ ...prev, [field]: value }));

  const validate = () => {
    if (!form.firstName.trim()) return "First name is required.";
    if (!form.lastName.trim())  return "Last name is required.";
    if (!form.email.includes("@")) return "Enter a valid email.";
    if (form.password.length < 8)  return "Password must be at least 8 characters.";
    if (form.password !== form.confirmPassword) return "Passwords do not match.";
    return null;
  };

  const handleSubmit = async () => {
    setError("");
    const err = validate();
    if (err) { setError(err); return; }
    setLoading(true);
    try {
      const res = await fetch(
        `${process.env.NEXT_PUBLIC_API_URL}/auth/register`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            firstName: form.firstName,
            lastName: form.lastName,
            email: form.email,
            password: form.password,
          }),
        }
      );
      const data = await res.json();
      if (!res.ok) {
        setError(data.message || "Registration failed.");
        return;
      }
      setSuccess(true);
      toast.success("Account created! Check your email for OTP.");
      // ✅ Redirect to OTP verification page with email
      setTimeout(() => {
        router.push(`/verify-otp?email=${encodeURIComponent(form.email)}&type=verify`);
      }, 1500);
    } catch {
      setError("Server error. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  if (success) {
    return (
      <div className={styles.page}>
        <div className={styles.card} style={{ textAlign: "center" }}>
          <div style={{ fontSize: "3rem", marginBottom: "16px" }}>📧</div>
          <h1 className={styles.heading}>Check Your Email</h1>
          <p className={styles.subheading} style={{ marginBottom: "24px", lineHeight: 1.7 }}>
            We sent a 6-digit OTP to<br />
            <strong style={{ color: "#c084fc" }}>{form.email}</strong><br /><br />
            Enter the code to verify your email.<br />
            After verification, <strong>admin will approve</strong> your account.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.page}>
      <Toaster position="top-right" />
      <div className={styles.card}>

        <div className={styles.logoWrap}>
          <img src="https://crm.qrs.ae/qrslogo.jpg" alt="QRS" className={styles.logoImg}
            onError={(e) => { (e.target as HTMLImageElement).style.display = "none"; }} />
        </div>

        <h1 className={styles.heading}>Create Account</h1>
        <p className={styles.subheading}>Register with your work email</p>

        <div className={styles.form}>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px" }}>
            <div className={styles.fieldWrap}>
              <label className={styles.label}>First Name</label>
              <div className={styles.inputWrap}>
                <span className={styles.inputIcon}><User size={15} /></span>
                <input className={styles.input} placeholder="John"
                  value={form.firstName} onChange={(e) => set("firstName", e.target.value)} />
              </div>
            </div>
            <div className={styles.fieldWrap}>
              <label className={styles.label}>Last Name</label>
              <div className={styles.inputWrap}>
                <span className={styles.inputIcon}><User size={15} /></span>
                <input className={styles.input} placeholder="Doe"
                  value={form.lastName} onChange={(e) => set("lastName", e.target.value)} />
              </div>
            </div>
          </div>

          <div className={styles.fieldWrap}>
            <label className={styles.label}>Email Address</label>
            <div className={styles.inputWrap}>
              <span className={styles.inputIcon}><Mail size={15} /></span>
              <input className={styles.input} type="email" placeholder="john@company.com"
                value={form.email} onChange={(e) => set("email", e.target.value)} />
            </div>
          </div>

          <div className={styles.fieldWrap}>
            <label className={styles.label}>Password</label>
            <div className={styles.inputWrap}>
              <span className={styles.inputIcon}><Lock size={15} /></span>
              <input className={styles.input}
                type={showPass ? "text" : "password"} placeholder="Min 8 characters"
                value={form.password} onChange={(e) => set("password", e.target.value)} />
              <button className={styles.eyeBtn} type="button" onClick={() => setShowPass(!showPass)}>
                {showPass ? <EyeOff size={15} /> : <Eye size={15} />}
              </button>
            </div>
          </div>

          <div className={styles.fieldWrap}>
            <label className={styles.label}>Confirm Password</label>
            <div className={styles.inputWrap}>
              <span className={styles.inputIcon}><Lock size={15} /></span>
              <input className={styles.input}
                type={showConfirm ? "text" : "password"} placeholder="Repeat password"
                value={form.confirmPassword}
                onChange={(e) => set("confirmPassword", e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && handleSubmit()} />
              <button className={styles.eyeBtn} type="button" onClick={() => setShowConfirm(!showConfirm)}>
                {showConfirm ? <EyeOff size={15} /> : <Eye size={15} />}
              </button>
            </div>
          </div>

          {error && <div className={styles.error}>{error}</div>}

          <button className={styles.btn} onClick={handleSubmit} disabled={loading}>
            <span className={styles.btnInner}>
              {loading && <span className={styles.spinner} />}
              {loading ? "Creating account..." : "Create Account"}
            </span>
          </button>

          <p style={{ textAlign: "center", fontSize: "0.82rem",
            color: "rgba(7, 3, 3, 0.99)", marginTop: "4px" }}>
            Already have an account?{" "}
            <Link href="/login" style={{ color: "#c084fc", fontWeight: 600 }}>Sign in</Link>
          </p>
        </div>
      </div>
    </div>
  );
}