"use client";

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

export default function ResetPasswordPage() {
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showPass, setShowPass] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);
  const router = useRouter();
  const supabase = createClient();

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

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

    if (password !== confirmPassword) {
      setError("كلمتا المرور غير متطابقتين");
      setLoading(false);
      return;
    }

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

    if (!isUrlValid) {
      // Local Developer Mode Intercept & Bypass
      await new Promise((resolve) => setTimeout(resolve, 1000));
      setSuccess(true);
      setLoading(false);
      return;
    }

    const { error } = await supabase.auth.updateUser({ password });

    if (error) {
      setError(error.message || "حدث خطأ أثناء تحديث كلمة المرور، يرجى المحاولة لاحقاً");
      setLoading(false);
      return;
    }

    setSuccess(true);
    setLoading(false);
  }

  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>

          <div className="space-y-4">
            <h2 className="text-xl font-bold text-white">تم تحديث كلمة المرور بنجاح</h2>
            <p className="text-[#8a8380] text-sm leading-relaxed">
              {!isUrlValid
                ? "(وضع المطور المحلي) تم محاكاة تحديث كلمة المرور بنجاح!"
                : "تم تعيين كلمة المرور الجديدة الخاصة بك بنجاح. يمكنك الآن تسجيل الدخول باستخدام كلمة المرور الجديدة."}
            </p>
          </div>

          <div className="pt-2">
            <Link
              href="/authentication/sign-in"
              className="w-full flex items-center justify-center bg-emerald-500 hover:bg-emerald-400 text-white font-bold py-3.5 rounded-xl transition-all text-xs shadow-lg shadow-emerald-500/20"
            >
              تسجيل الدخول بالبيانات الجديدة 🚀
            </Link>
          </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-8">
          <Link href="/" className="inline-flex items-center gap-2 mb-6">
            <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 leading-relaxed">
            أدخل كلمة المرور الجديدة التي ترغب في استخدامها لحسابك.
          </p>
        </div>

        {/* Form */}
        <form onSubmit={handleResetPassword} className="space-y-4">
          {/* New Password */}
          <div>
            <label className="block text-sm text-[#b8b3b0] mb-2" htmlFor="new-password">
              كلمة المرور الجديدة
            </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="new-password"
                type={showPass ? "text" : "password"}
                value={password}
                onChange={(e) => setPassword(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-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>

          {/* Confirm Password */}
          <div>
            <label className="block text-sm text-[#b8b3b0] mb-2" htmlFor="confirm-password">
              تأكيد كلمة المرور الجديدة
            </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="confirm-password"
                type={showPass ? "text" : "password"}
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(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-10 text-sm outline-none transition-colors"
                dir="ltr"
              />
            </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>
        </form>

        {/* Back Link */}
        <p className="text-center text-sm text-[#8a8380] mt-6">
          <Link href="/authentication/sign-in" className="inline-flex items-center gap-1.5 text-emerald-400 hover:text-emerald-300 font-medium">
            <ArrowRight className="w-4 h-4" />
            <span>العودة لتسجيل الدخول</span>
          </Link>
        </p>
      </div>
    </motion.div>
  );
}
