"use client";
import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import {
  Eye, EyeOff, ArrowRight, CheckCircle, Building2, Mail, Lock,
} from "lucide-react";

// ── OAuth icons ───────────────────────────────────────────────────────────────
function GoogleIcon() {
  return (
    <svg viewBox="0 0 24 24" className="w-5 h-5" fill="none">
      <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
      <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
      <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z" fill="#FBBC05"/>
      <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
    </svg>
  );
}

function GitHubIcon() {
  return (
    <svg viewBox="0 0 24 24" className="w-5 h-5" fill="currentColor">
      <path d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"/>
    </svg>
  );
}

function OrDivider() {
  return (
    <div className="flex items-center gap-3 my-5">
      <div className="flex-1 h-px bg-gray-200" />
      <span className="text-xs text-gray-400 font-medium">or</span>
      <div className="flex-1 h-px bg-gray-200" />
    </div>
  );
}

const features = [
  "9 auto-reminder templates",
  "WhatsApp from your number",
  "Patient confirmation tracking",
  "No-show recovery flows",
  "Real-time delivery status",
  "14-day free trial",
];

export default function RegisterPage() {
  const router    = useRouter();
  const nameRef   = useRef<HTMLInputElement>(null);
  const [step, setStep] = useState<1 | 2>(1);
  const [form, setForm] = useState({
    clinicName: "", email: "", password: "", confirmPassword: "",
  });
  const [showPw,  setShowPw]   = useState(false);
  const [error,   setError]    = useState("");
  const [loading, setLoading]  = useState(false);
  const [oauthLoading, setOauthLoading] = useState<string | null>(null);
  const [ready,   setReady]    = useState(false);

  useEffect(() => { setReady(true); setTimeout(() => nameRef.current?.focus(), 100); }, []);
  useEffect(() => { if (error) setError(""); }, [form]);

  const u = (f: string, v: string) => setForm(p => ({ ...p, [f]: v }));

  // Password strength
  const strength = (() => {
    const p = form.password;
    if (!p) return { s: 0, l: "", c: "" };
    let s = 0;
    if (p.length >= 8)         s++;
    if (p.length >= 12)        s++;
    if (/[A-Z]/.test(p))       s++;
    if (/[0-9]/.test(p))       s++;
    if (/[^A-Za-z0-9]/.test(p)) s++;
    return s <= 1
      ? { s: 1, l: "Weak",   c: "bg-red-400"     }
      : s <= 2
      ? { s: 2, l: "Fair",   c: "bg-amber-400"   }
      : s <= 3
      ? { s: 3, l: "Good",   c: "bg-primary-400" }
      : { s: 4, l: "Strong", c: "bg-emerald-500" };
  })();

  const s1ok  = form.clinicName.length >= 2 && form.email.includes("@");
  const s2ok  = form.password.length >= 8 && form.password === form.confirmPassword;
  const match = form.confirmPassword.length > 0 && form.password === form.confirmPassword;

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!s2ok) return;
    setLoading(true); setError("");
    try {
      const res  = await fetch("/api/auth/register", {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify({
          clinicName: form.clinicName,
          email:      form.email,
          password:   form.password,
        }),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.error); return; }
      localStorage.setItem("clinera_email", form.email);
      router.push("/dashboard");
    } catch {
      setError("Something went wrong. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  const handleOAuth = (provider: "google" | "github") => {
    setOauthLoading(provider);
    window.location.href = `/api/auth/oauth/${provider}`;
  };

  return (
    <div className="min-h-screen flex">
      {/* ── Left: Brand panel ─────────────────────────────────────────────── */}
      <div className="hidden lg:flex lg:w-[46%] relative overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-br from-[#0a0a1f] via-[#0f0f2d] to-[#12122e]" />
        <div
          className="absolute inset-0 opacity-[0.03]"
          style={{
            backgroundImage:
              "linear-gradient(rgba(255,255,255,.3) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.3) 1px, transparent 1px)",
            backgroundSize: "40px 40px",
          }}
        />
        <div className="absolute bottom-0 right-0 w-96 h-96 bg-primary-500/8 rounded-full blur-[100px]" />

        <div className="relative z-10 flex flex-col justify-between p-10 w-full">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-primary-500 to-primary-700 flex items-center justify-center shadow-lg shadow-primary-500/20">
              <span className="text-white font-bold text-lg">C</span>
            </div>
            <span className="text-xl font-bold text-white tracking-tight">CLINERA</span>
          </div>

          <div className="space-y-6">
            <div>
              <p className="text-xs font-semibold text-primary-400 uppercase tracking-widest mb-3">
                Everything you get
              </p>
              <h2 className="text-3xl font-bold text-white leading-[1.2] mb-4">
                Your clinic, on<br />
                <span className="gradient-text">autopilot.</span>
              </h2>
              <p className="text-gray-400 text-sm leading-relaxed">
                Start free, no credit card required. 14-day trial with all features.
              </p>
            </div>

            <div className="space-y-2.5">
              {features.map((f, i) => (
                <div key={i} className="flex items-center gap-3">
                  <div className="w-5 h-5 rounded-full bg-primary-500/20 flex items-center justify-center shrink-0">
                    <CheckCircle size={12} className="text-primary-400" />
                  </div>
                  <span className="text-sm text-gray-300">{f}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="text-[11px] text-gray-600 flex items-center gap-4">
            <span>🔒 Encrypted</span>
            <span>🌍 GDPR ready</span>
            <span>⚡ 99.9% uptime</span>
          </div>
        </div>
      </div>

      {/* ── Right: Register form ───────────────────────────────────────────── */}
      <div className="flex-1 flex items-center justify-center px-6 py-12 bg-[#f8fafc] relative overflow-y-auto">
        <div
          className="absolute inset-0 opacity-[0.3] pointer-events-none"
          style={{ backgroundImage: "radial-gradient(#e2e8f0 0.5px, transparent 0.5px)", backgroundSize: "24px 24px" }}
        />

        <div className={`relative w-full max-w-[400px] transition-all duration-500 ${ready ? "opacity-100 translate-y-0" : "opacity-0 translate-y-6"}`}>
          {/* Mobile logo */}
          <div className="lg:hidden flex items-center justify-center gap-2.5 mb-8">
            <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-primary-500 to-primary-700 flex items-center justify-center">
              <span className="text-white font-bold text-lg">C</span>
            </div>
            <span className="text-2xl font-bold tracking-tight text-dark">CLINERA</span>
          </div>

          <div className="mb-6">
            <h1 className="text-2xl font-bold text-dark">Create your clinic</h1>
            <p className="text-muted text-sm mt-1">14-day free trial · No credit card</p>
          </div>

          {/* ── OAuth Buttons ────────────────────────────────────────────── */}
          <div className="space-y-2.5 mb-1">
            <button
              type="button"
              onClick={() => handleOAuth("google")}
              disabled={!!oauthLoading || loading}
              className="w-full flex items-center justify-center gap-3 px-4 py-2.5 bg-white border border-gray-200 rounded-xl text-sm font-medium text-gray-700 hover:bg-gray-50 hover:border-gray-300 transition-all disabled:opacity-60 shadow-sm"
            >
              {oauthLoading === "google"
                ? <div className="w-4 h-4 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin" />
                : <GoogleIcon />}
              Sign up with Google
            </button>
            <button
              type="button"
              onClick={() => handleOAuth("github")}
              disabled={!!oauthLoading || loading}
              className="w-full flex items-center justify-center gap-3 px-4 py-2.5 bg-gray-900 border border-gray-800 rounded-xl text-sm font-medium text-white hover:bg-gray-800 transition-all disabled:opacity-60 shadow-sm"
            >
              {oauthLoading === "github"
                ? <div className="w-4 h-4 border-2 border-gray-600 border-t-white rounded-full animate-spin" />
                : <GitHubIcon />}
              Sign up with GitHub
            </button>
          </div>

          <OrDivider />

          {/* ── Step indicator ───────────────────────────────────────────── */}
          <div className="flex items-center gap-2 mb-5">
            {[1, 2].map((n) => (
              <div key={n} className="flex items-center gap-2">
                <div className={`w-6 h-6 rounded-full flex items-center justify-center text-[11px] font-bold transition-all ${step >= n ? "bg-primary-600 text-white" : "bg-gray-200 text-gray-400"}`}>
                  {step > n ? <CheckCircle size={13} /> : n}
                </div>
                {n < 2 && <div className={`flex-1 h-px w-8 transition-all ${step > n ? "bg-primary-400" : "bg-gray-200"}`} />}
              </div>
            ))}
            <span className="ml-2 text-xs text-gray-500">
              {step === 1 ? "Clinic details" : "Set password"}
            </span>
          </div>

          <div className="card p-7">
            <form onSubmit={step === 1 ? (e) => { e.preventDefault(); if (s1ok) setStep(2); } : submit} className="space-y-4">
              {error && (
                <div className="flex items-start gap-2.5 p-3 bg-red-50 border border-red-100 rounded-xl">
                  <span className="text-red-400 text-sm mt-0.5">⚠</span>
                  <p className="text-xs text-red-600 font-medium">{error}</p>
                </div>
              )}

              {/* ── Step 1 ──────────────────────────────────────────────── */}
              {step === 1 && (
                <>
                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1.5">
                      <Building2 size={11} className="inline mr-1" /> Clinic name
                    </label>
                    <input
                      ref={nameRef}
                      type="text"
                      value={form.clinicName}
                      onChange={e => u("clinicName", e.target.value)}
                      placeholder="Glow Aesthetics Clinic"
                      required
                      minLength={2}
                      className="input"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1.5">
                      <Mail size={11} className="inline mr-1" /> Email address
                    </label>
                    <input
                      type="email"
                      value={form.email}
                      onChange={e => u("email", e.target.value)}
                      placeholder="you@clinic.com"
                      required
                      autoComplete="email"
                      className="input"
                    />
                  </div>
                  <button type="submit" disabled={!s1ok} className="btn-primary w-full py-3 group">
                    Continue
                    <ArrowRight size={16} className="group-hover:translate-x-1 transition-transform" />
                  </button>
                </>
              )}

              {/* ── Step 2 ──────────────────────────────────────────────── */}
              {step === 2 && (
                <>
                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1.5">
                      <Lock size={11} className="inline mr-1" /> Password
                    </label>
                    <div className="relative">
                      <input
                        type={showPw ? "text" : "password"}
                        value={form.password}
                        onChange={e => u("password", e.target.value)}
                        placeholder="At least 8 characters"
                        required
                        autoFocus
                        autoComplete="new-password"
                        className="input pr-10"
                      />
                      <button
                        type="button"
                        onClick={() => setShowPw(!showPw)}
                        className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                        tabIndex={-1}
                      >
                        {showPw ? <EyeOff size={16} /> : <Eye size={16} />}
                      </button>
                    </div>

                    {/* Strength bar */}
                    {form.password && (
                      <div className="mt-2 space-y-1">
                        <div className="flex gap-1">
                          {[1,2,3,4].map(i => (
                            <div key={i} className={`h-1 flex-1 rounded-full transition-all ${i <= strength.s ? strength.c : "bg-gray-200"}`} />
                          ))}
                        </div>
                        <p className={`text-[11px] font-medium ${strength.s <= 1 ? "text-red-500" : strength.s <= 2 ? "text-amber-500" : "text-emerald-600"}`}>
                          {strength.l}
                        </p>
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1.5">Confirm password</label>
                    <div className="relative">
                      <input
                        type={showPw ? "text" : "password"}
                        value={form.confirmPassword}
                        onChange={e => u("confirmPassword", e.target.value)}
                        placeholder="Repeat your password"
                        required
                        autoComplete="new-password"
                        className={`input pr-10 ${form.confirmPassword ? (match ? "ring-1 ring-emerald-400" : "ring-1 ring-red-300") : ""}`}
                      />
                      {form.confirmPassword && (
                        <span className={`absolute right-3 top-1/2 -translate-y-1/2 text-sm ${match ? "text-emerald-500" : "text-red-400"}`}>
                          {match ? "✓" : "✗"}
                        </span>
                      )}
                    </div>
                  </div>

                  <div className="flex gap-2.5">
                    <button
                      type="button"
                      onClick={() => setStep(1)}
                      className="btn-secondary px-4 py-3"
                    >
                      Back
                    </button>
                    <button
                      type="submit"
                      disabled={loading || !s2ok}
                      className="btn-primary flex-1 py-3 group"
                    >
                      {loading ? (
                        <>
                          <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                          Creating account...
                        </>
                      ) : (
                        <>
                          Create Clinic
                          <ArrowRight size={16} className="group-hover:translate-x-1 transition-transform" />
                        </>
                      )}
                    </button>
                  </div>
                </>
              )}
            </form>
          </div>

          <p className="text-center text-sm text-muted mt-6">
            Already have an account?{" "}
            <Link href="/login" className="text-primary-600 font-semibold hover:text-primary-500 transition-colors">
              Sign in
            </Link>
          </p>

          <p className="text-center text-[10px] text-gray-400 mt-4 leading-relaxed">
            By creating an account you agree to our{" "}
            <span className="underline cursor-pointer hover:text-gray-600">Terms</span>
            {" "}and{" "}
            <span className="underline cursor-pointer hover:text-gray-600">Privacy Policy</span>.
          </p>
        </div>
      </div>
    </div>
  );
}
