"use client";
import { useState, useEffect, useRef } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import {
  Eye, EyeOff, ArrowRight, Shield, Zap, Users, MessageSquare,
  CheckCircle, AlertCircle,
} from "lucide-react";
import { Suspense } from "react";

// ── OAuth provider icons (inline SVG for zero-dep) ───────────────────────────
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>
  );
}

// ── Divider ───────────────────────────────────────────────────────────────────
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>
  );
}

// ── Inner component (uses useSearchParams) ────────────────────────────────────
function LoginForm() {
  const router       = useRouter();
  const searchParams = useSearchParams();
  const emailRef     = useRef<HTMLInputElement>(null);

  const [email,    setEmail]   = useState("");
  const [password, setPassword] = useState("");
  const [showPw,   setShowPw]  = useState(false);
  const [error,    setError]   = useState("");
  const [loading,  setLoading] = useState(false);
  const [oauthLoading, setOauthLoading] = useState<string | null>(null);
  const [shake,    setShake]   = useState(false);
  const [ready,    setReady]   = useState(false);

  useEffect(() => {
    setReady(true);
    const saved = localStorage.getItem("clinera_email");
    if (saved) setEmail(saved);
    setTimeout(() => emailRef.current?.focus(), 100);

    // Show OAuth error if redirected back from callback
    const err = searchParams.get("error");
    if (err) setError(decodeURIComponent(err));
  }, [searchParams]);

  useEffect(() => { if (error) setError(""); }, [email, password]);

  const triggerShake = () => { setShake(true); setTimeout(() => setShake(false), 600); };

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

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

  const valid = email.includes("@") && password.length >= 8;

  return (
    <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-8">
        <h1 className="text-2xl font-bold text-dark">Welcome back</h1>
        <p className="text-muted text-sm mt-1">Sign in to your clinic dashboard</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 />}
          Continue 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 />}
          Continue with GitHub
        </button>
      </div>

      <OrDivider />

      {/* ── Email / Password Form ─────────────────────────────────────────── */}
      <div className={`card p-7 ${shake ? "animate-shake" : ""}`}>
        <form onSubmit={submit} className="space-y-4">
          {error && (
            <div className="flex items-center gap-2.5 p-3 bg-red-50 border border-red-100 rounded-xl animate-fade-in">
              <AlertCircle size={15} className="text-red-400 shrink-0" />
              <p className="text-xs text-red-600 font-medium">{error}</p>
            </div>
          )}

          <div>
            <label className="block text-xs font-semibold text-gray-600 mb-1.5">Email</label>
            <input
              ref={emailRef}
              type="email"
              value={email}
              onChange={e => setEmail(e.target.value)}
              placeholder="you@clinic.com"
              required
              autoComplete="email"
              className="input"
            />
          </div>

          <div>
            <label className="block text-xs font-semibold text-gray-600 mb-1.5">Password</label>
            <div className="relative">
              <input
                type={showPw ? "text" : "password"}
                value={password}
                onChange={e => setPassword(e.target.value)}
                placeholder="••••••••"
                required
                autoComplete="current-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 p-0.5"
                tabIndex={-1}
              >
                {showPw ? <EyeOff size={16} /> : <Eye size={16} />}
              </button>
            </div>
          </div>

          <button
            type="submit"
            disabled={loading || !!oauthLoading || !valid}
            className="btn-primary w-full py-3 group"
          >
            {loading ? (
              <>
                <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                Signing in...
              </>
            ) : (
              <>
                Sign In
                <ArrowRight size={16} className="group-hover:translate-x-1 transition-transform" />
              </>
            )}
          </button>
        </form>
      </div>

      <p className="text-center text-sm text-muted mt-6">
        No account?{" "}
        <Link href="/register" className="text-primary-600 font-semibold hover:text-primary-500 transition-colors">
          Register your clinic
        </Link>
      </p>

      <div className="flex items-center justify-center gap-5 mt-8 text-[10px] text-gray-400">
        <span className="flex items-center gap-1"><Shield size={10} /> Encrypted</span>
        <span className="flex items-center gap-1"><CheckCircle size={10} /> HIPAA-aware</span>
        <span className="flex items-center gap-1"><Zap size={10} /> 99.9% uptime</span>
      </div>

      <style jsx>{`
        @keyframes shake { 0%,100%{transform:translateX(0)} 20%,60%{transform:translateX(-8px)} 40%,80%{transform:translateX(8px)} }
        .animate-shake { animation: shake 0.5s ease; }
      `}</style>
    </div>
  );
}

// ── Page (wraps form in Suspense for useSearchParams) ─────────────────────────
export default function LoginPage() {
  return (
    <div className="min-h-screen flex">
      {/* ── Left: Dark 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 top-1/4 left-1/4 w-96 h-96 bg-primary-500/10 rounded-full blur-[100px]" />
        <div className="absolute bottom-1/4 right-1/4 w-64 h-64 bg-blue-500/8 rounded-full blur-[80px]" />

        <div className="relative z-10 flex flex-col justify-between p-10 w-full">
          {/* Logo */}
          <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>

          {/* Hero */}
          <div className="space-y-8">
            <div>
              <h2 className="text-4xl font-bold text-white leading-[1.15] mb-4">
                Stop losing patients.<br />
                <span className="gradient-text">Start filling chairs.</span>
              </h2>
              <p className="text-gray-400 text-[15px] leading-relaxed max-w-md">
                Automatic WhatsApp reminders that turn leads into patients who actually show up.
                From your clinic&apos;s own number.
              </p>
            </div>

            {/* Stats */}
            <div className="grid grid-cols-3 gap-3">
              {[
                { icon: Users,         val: "340+",  desc: "Clinics" },
                { icon: MessageSquare, val: "98%",   desc: "Delivery rate" },
                { icon: Zap,           val: "<60s",  desc: "Response time" },
              ].map((s, i) => (
                <div key={i} className="bg-white/[0.04] border border-white/[0.06] rounded-xl p-4 backdrop-blur-sm">
                  <s.icon size={15} className="text-primary-400 mb-2" />
                  <p className="text-2xl font-bold text-white">{s.val}</p>
                  <p className="text-[11px] text-gray-500">{s.desc}</p>
                </div>
              ))}
            </div>
          </div>

          {/* Testimonial */}
          <div className="bg-white/[0.03] border border-white/[0.06] rounded-xl p-5 backdrop-blur-sm">
            <p className="text-sm text-gray-300 leading-relaxed italic mb-3">
              &ldquo;We went from 13% to 41% show-up rate in the first month. The reminders pay for themselves 10x over.&rdquo;
            </p>
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 rounded-full bg-gradient-to-br from-primary-500 to-primary-700 flex items-center justify-center">
                <span className="text-[10px] font-bold text-white">S</span>
              </div>
              <div>
                <p className="text-xs font-semibold text-white">Dr. Sarah Al-Rashid</p>
                <p className="text-[10px] text-gray-500">Glow Aesthetics · Riyadh</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* ── Right: Login form ─────────────────────────────────────────────── */}
      <div className="flex-1 flex items-center justify-center px-6 py-12 bg-[#f8fafc] relative">
        <div
          className="absolute inset-0 opacity-[0.3] pointer-events-none"
          style={{ backgroundImage: "radial-gradient(#e2e8f0 0.5px, transparent 0.5px)", backgroundSize: "24px 24px" }}
        />
        <Suspense fallback={<div className="w-8 h-8 border-2 border-primary-300 border-t-primary-600 rounded-full animate-spin" />}>
          <LoginForm />
        </Suspense>
      </div>
    </div>
  );
}
