"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { motion } from "framer-motion";
import { Zap, Mail, Lock, User, Eye, EyeOff, Loader2, Check } from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import { cn } from "@/lib/utils";

const GoogleIcon = () => (
  <svg className="w-5 h-5 flex-shrink-0" viewBox="0 0 24 24">
    <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.06H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.94l2.85-2.22.81-.63z"
      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.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z"
      fill="#EA4335"
    />
  </svg>
);

const benefits = [
  "حملة إعلانية مجانية للأبد",
  "حماية النقرات الوهمية مشمولة",
  "لوحة تحليلات احترافية",
  "لا بطاقة ائتمان مطلوبة",
];

export default function SignUpPage() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPass, setShowPass] = useState(false);
  const [loading, setLoading] = useState(false);
  const [oauthLoading, setOauthLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);
  const router = useRouter();
  const supabase = createClient();

  async function handleSignUp(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setError("");

    if (password.length < 8) {
      setError("كلمة المرور يجب أن تكون 8 أحرف على الأقل");
      setLoading(false);
      return;
    }

    const rawUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
    const isUrlValid = rawUrl && rawUrl.startsWith("http");

    if (!isUrlValid) {
      // Local Developer Mode Intercept & Bypass
      localStorage.setItem("local_developer_user", JSON.stringify({
        email,
        user_metadata: { full_name: name }
      }));
      setSuccess(true);
      setLoading(false);
      return;
    }

    const { error } = await supabase.auth.signUp({
      email,
      password,
      options: { data: { full_name: name } },
    });

    if (error) {
      setError(error.message === "User already registered" ? "البريد الإلكتروني مسجّل مسبقاً" : "حدث خطأ، يرجى المحاولة مجدداً");
      setLoading(false);
      return;
    }

    setSuccess(true);
    setLoading(false);
  }

  async function handleGoogleSignIn() {
    setOauthLoading(true);
    await supabase.auth.signInWithOAuth({
      provider: "google",
      options: { redirectTo: `${location.origin}/api/auth/callback` },
    });
  }

  const rawUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
  const isUrlValid = rawUrl && rawUrl.startsWith("http");

  if (success) {
    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="w-full max-w-md text-center"
      >
        <div className="bg-[#101010] border border-emerald-500/30 rounded-2xl p-8 space-y-6">
          <div className="w-16 h-16 rounded-full bg-emerald-500/10 border border-emerald-500/30 flex items-center justify-center mx-auto">
            <Check className="w-8 h-8 text-emerald-400" />
          </div>
          
          {!isUrlValid ? (
            <div className="space-y-4">
              <h2 className="text-xl font-bold text-white">🎉 مرحباً بك في بيئة المطورين!</h2>
              <p className="text-[#8a8380] text-xs leading-relaxed">
                تم تسجيل حساب المسؤول المحلي الخاص بك **({name})** بنجاح وتأسيس جلسة عمل آمنة ومستقلة 100%!
              </p>
              <Link
                href="/dashboard"
                className="w-full flex items-center justify-center bg-emerald-500 hover:bg-emerald-400 text-white font-bold py-3 rounded-xl transition-all text-xs"
              >
                الدخول المباشر إلى لوحة التحكم 🚀
              </Link>
            </div>
          ) : (
            <div className="space-y-2">
              <h2 className="text-xl font-bold text-white">تحقق من بريدك الإلكتروني</h2>
              <p className="text-[#8a8380] text-sm">
                أرسلنا رابط تأكيد إلى <span className="text-emerald-400">{email}</span>
              </p>
            </div>
          )}
        </div>
      </motion.div>
    );
  }

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      className="w-full max-w-md"
    >
      <div className="bg-[#101010] border border-gray-800 rounded-2xl p-8 shadow-2xl">
        {/* Logo */}
        <div className="text-center mb-6">
          <Link href="/" className="inline-flex items-center gap-2 mb-4">
            <div className="w-9 h-9 rounded-full border border-emerald-500 flex items-center justify-center">
              <Zap className="w-4 h-4 text-emerald-500" />
            </div>
            <span className="text-white font-bold text-xl">برو كود ادز</span>
          </Link>
          <h1 className="text-2xl font-bold text-white mb-1">أنشئ حسابك المجاني</h1>
          <p className="text-[#8a8380] text-sm">بدون بطاقة ائتمان · إلغاء في أي وقت</p>
        </div>

        {/* Benefits */}
        <div className="grid grid-cols-2 gap-2 mb-6">
          {benefits.map((b) => (
            <div key={b} className="flex items-center gap-1.5 text-xs text-[#8a8380]">
              <Check className="w-3 h-3 text-emerald-500 flex-shrink-0" />
              {b}
            </div>
          ))}
        </div>

        {/* Google OAuth */}
        <button
          onClick={handleGoogleSignIn}
          disabled={oauthLoading}
          className="w-full flex items-center justify-center gap-3 bg-[#161b27] hover:bg-[#1e2535] border border-gray-700 text-white py-3 rounded-xl transition-all mb-5 disabled:opacity-50 cursor-pointer"
        >
          {oauthLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : <GoogleIcon />}
          <span className="text-sm font-medium">التسجيل بحساب Google</span>
        </button>

        <div className="flex items-center gap-3 mb-5">
          <div className="flex-1 h-px bg-gray-800" />
          <span className="text-xs text-gray-600">أو بالبريد الإلكتروني</span>
          <div className="flex-1 h-px bg-gray-800" />
        </div>

        {/* Form */}
        <form onSubmit={handleSignUp} className="space-y-4">
          <div>
            <label className="block text-sm text-[#b8b3b0] mb-2" htmlFor="name">الاسم الكامل</label>
            <div className="relative">
              <User className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-600" />
              <input
                id="name"
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                required
                placeholder="محمد أحمد"
                className="w-full bg-[#161b27] border border-gray-700 focus:border-emerald-500 text-white placeholder-gray-600 rounded-xl py-3 pr-10 pl-4 text-sm outline-none transition-colors"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm text-[#b8b3b0] mb-2" htmlFor="email-signup">البريد الإلكتروني</label>
            <div className="relative">
              <Mail className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-600" />
              <input
                id="email-signup"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
                placeholder="you@example.com"
                className="w-full bg-[#161b27] border border-gray-700 focus:border-emerald-500 text-white placeholder-gray-600 rounded-xl py-3 pr-10 pl-4 text-sm outline-none transition-colors"
                dir="ltr"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm text-[#b8b3b0] mb-2" htmlFor="password-signup">كلمة المرور</label>
            <div className="relative">
              <Lock className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-600" />
              <input
                id="password-signup"
                type={showPass ? "text" : "password"}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
                minLength={8}
                placeholder="8 أحرف على الأقل"
                className="w-full bg-[#161b27] border border-gray-700 focus:border-emerald-500 text-white placeholder-gray-600 rounded-xl py-3 pr-10 pl-10 text-sm outline-none transition-colors"
                dir="ltr"
              />
              <button type="button" onClick={() => setShowPass(!showPass)} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-600 hover:text-gray-400">
                {showPass ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
              </button>
            </div>
          </div>

          {error && (
            <motion.p initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="text-red-400 text-sm text-center bg-red-500/10 border border-red-500/20 rounded-lg py-2">
              {error}
            </motion.p>
          )}

          <button
            type="submit"
            disabled={loading}
            className={cn(
              "w-full flex items-center justify-center gap-2 bg-emerald-500 hover:bg-emerald-400 text-white font-semibold py-3.5 rounded-xl transition-all shadow-lg shadow-emerald-500/20",
              loading && "opacity-70 cursor-not-allowed"
            )}
          >
            {loading && <Loader2 className="w-4 h-4 animate-spin" />}
            إنشاء حساب مجاني
          </button>

          <p className="text-center text-xs text-gray-600">
            بالتسجيل تقبل{" "}
            <Link href="/terms" className="text-emerald-400 hover:text-emerald-300">شروط الخدمة</Link>
            {" "}و{" "}
            <Link href="/privacy" className="text-emerald-400 hover:text-emerald-300">سياسة الخصوصية</Link>
          </p>
        </form>

        <p className="text-center text-sm text-[#8a8380] mt-5">
          لديك حساب؟{" "}
          <Link href="/authentication/sign-in" className="text-emerald-400 hover:text-emerald-300 font-medium">
            تسجيل الدخول
          </Link>
        </p>
      </div>
    </motion.div>
  );
}
