"use client";

import { useState } from "react";
import { Mail, Fingerprint, ArrowLeft, ArrowRight, CheckCircle } from "lucide-react";
import { useLanguage } from "@/components/language-provider";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";

export default function ForgotPasswordPage() {
  const { t, lang, dir } = useLanguage();
  const Arrow = lang === "fa" ? ArrowRight : ArrowLeft;

  const [email, setEmail] = useState("");
  const [step, setStep] = useState<"request" | "sent">("request");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setLoading(true);

    try {
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/password/reset/`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.detail || data.error || "Request failed");
      }

      setStep("sent");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Request failed");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-ink px-4 py-12">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <Link href="#top" className="inline-flex items-center gap-2.5 font-semibold text-white mb-6">
            <span className="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-gradient shadow-lg shadow-brand-900/40">
              <Fingerprint className="h-6 w-6 text-white" />
            </span>
            <span className="text-xl tracking-tight">{process.env.NEXT_PUBLIC_SITE_NAME || "MyAccount Hamsoo"}</span>
          </Link>
          {step === "request" ? (
            <>
              <h1 className="text-2xl font-bold text-white">{lang === "fa" ? "بازیابی رمز عبور" : "Reset Password"}</h1>
              <p className="mt-2 text-slate-400">
                {lang === "fa" ? "ایمیل خود را وارد کنید تا لینک بازیابی ارسال شود" : "Enter your email to receive a reset link"}
              </p>
            </>
          ) : (
            <>
              <div className="mb-4 flex justify-center">
                <CheckCircle className="h-16 w-16 text-emerald-400" />
              </div>
              <h1 className="text-2xl font-bold text-white">{lang === "fa" ? "ایمیل ارسال شد" : "Email Sent"}</h1>
              <p className="mt-2 text-slate-400">
                {lang === "fa"
                  ? "اگر ایمیل در سیستم ثبت باشد، لینک بازیابی ارسال می‌شود"
                  : "If the email exists in our system, a reset link has been sent"}
              </p>
            </>
          )}
        </div>

        <div className="card">
          {error && (
            <div className="mb-4 rounded-lg bg-rose-500/15 border border-rose-500/30 p-3 text-sm text-rose-300" role="alert">
              {error}
            </div>
          )}

          {step === "request" && (
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label htmlFor="email" className="block text-sm font-medium text-slate-300 mb-1.5">
                  {lang === "fa" ? "ایمیل" : "Email"}
                </label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-slate-500 rtl:hidden" />
                  <Mail className="absolute right-3 top-1/2 -translate-y-1/2 h-5 w-5 text-slate-500 hidden rtl:block" />
                  <input
                    id="email"
                    type="email"
                    autoComplete="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    required
                    className="w-full pl-10 pr-4 py-2.5 rounded-lg border border-white/10 bg-white/5 text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-brand-500/50 focus:border-transparent"
                    placeholder={lang === "fa" ? "you@example.com" : "you@example.com"}
                    dir="ltr"
                  />
                </div>
              </div>

              <Button type="submit" className="w-full" size="lg" disabled={loading}>
                {loading
                  ? lang === "fa"
                    ? "در حال ارسال..."
                    : "Sending..."
                  : lang === "fa"
                  ? "ارسال لینک بازیابی"
                  : "Send Reset Link"}
                <Arrow className="h-5 w-5 rtl:rotate-180" />
              </Button>
            </form>
          )}

          {step === "sent" && (
            <div className="text-center space-y-4">
              <Button variant="secondary" className="w-full" onClick={() => window.history.back()}>
                <Arrow className="h-5 w-5 rtl:rotate-180" />
                {lang === "fa" ? "بازگشت به ورود" : "Back to Sign In"}
              </Button>
              <p className="text-sm text-slate-500">
                {lang === "fa" ? "ایمیل را پیدا نکردید؟" : "Didn't receive the email?"}{" "}
                <a href="#/forgot-password" className="text-brand-300 hover:text-brand-200 font-medium">
                  {lang === "fa" ? "ارسال مجدد" : "Resend"}
                </a>
              </p>
            </div>
          )}
        </div>

        <div className="mt-6 text-center text-xs text-slate-500">
          <Badge className="mb-2">
            <Fingerprint className="h-3 w-3" />
            {lang === "fa" ? "مرکز حساب همسو" : "MyAccount Hamsoo"}
          </Badge>
        </div>
      </div>
    </div>
  );
}

function Link({ href, children, className }: { href: string; children: React.ReactNode; className?: string }) {
  return <a href={href} className={className}>{children}</a>;
}
