"use client";

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

export default function ForgotPasswordPage() {
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);
  const supabase = createClient();

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

    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.resetPasswordForEmail(email, {
      redirectTo: `${window.location.origin}/authentication/reset-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>
            {!isUrlValid ? (
              <div className="space-y-3">
                <p className="text-[#8a8380] text-xs leading-relaxed">
                  (وضع المطور المحلي) لقد قمنا بمحاكاة إرسال رابط استعادة كلمة المرور بنجاح للبريد:
                </p>
                <p className="text-emerald-400 text-sm font-semibold dir-ltr">{email}</p>
                <div className="pt-2">
                  <Link
                    href="/authentication/reset-password"
                    className="inline-flex items-center gap-1.5 text-xs text-emerald-400 hover:text-emerald-300 transition-colors"
                  >
                    <span>الانتقال لصفحة تعيين كلمة المرور الجديدة</span>
                    <ArrowRight className="w-3.5 h-3.5 rotate-180" />
                  </Link>
                </div>
              </div>
            ) : (
              <p className="text-[#8a8380] text-sm leading-relaxed">
                أرسلنا رابط إعادة تعيين كلمة المرور إلى البريد الإلكتروني الخاص بك. يرجى التحقق من صندوق الوارد والرسائل غير المرغوب فيها (Spam).
              </p>
            )}
          </div>

          <div className="pt-2">
            <Link
              href="/authentication/sign-in"
              className="flex items-center justify-center gap-2 text-xs text-gray-500 hover:text-white transition-colors"
            >
              <ArrowRight className="w-4 h-4" />
              <span>العودة إلى تسجيل الدخول</span>
            </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={handleResetRequest} className="space-y-6">
          <div>
            <label className="block text-sm text-[#b8b3b0] mb-2" htmlFor="email-forgot">
              البريد الإلكتروني
            </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-forgot"
                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>

          {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>
  );
}
