"use client";

import { useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { Loader2, ArrowLeft, Mail } from "lucide-react";
import { authApi } from "@/lib/api/auth";
import { ApiException } from "@/lib/api/client";
import { toast } from "sonner";

export default function ForgotPasswordPage() {
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [sent, setSent] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [fieldError, setFieldError] = useState<string | null>(null);

  const inputClass =
    "w-full px-4 py-3 border border-gray-200 rounded-xl text-sm text-gray-900 placeholder:text-gray-400 bg-white focus:outline-none focus:ring-2 focus:ring-[#CC1414]/20 focus:border-[#CC1414]";

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setFieldError(null);
    setLoading(true);
    try {
      await authApi.forgotPassword(email.trim());
      setSent(true);
      toast.success("If the account exists, a reset link has been sent.");
    } catch (err) {
      if (err instanceof ApiException) {
        setError(err.message);
        if (err.errors?.email?.length) setFieldError(err.errors.email[0]);
        toast.error(err.message);
      } else {
        setError("Something went wrong. Please try again.");
        toast.error("Something went wrong. Please try again.");
      }
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-red-50 flex items-start justify-center px-4 pt-10 pb-10">
      <div className="w-full max-w-md">
        <div className="text-center mb-5">
          <Link href="/" className="inline-flex items-center">
            <Image src="/logo.png" alt="Biznie" width={220} height={58} className="h-12 w-auto" priority />
          </Link>
          <p className="text-gray-500 text-sm mt-2">India&apos;s B2B Raw Materials Platform</p>
        </div>

        <div className="bg-white rounded-2xl shadow-xl border border-gray-100 p-8">
          <h1 className="text-xl font-bold text-gray-900 mb-1">Forgot password</h1>
          <p className="text-sm text-gray-500 mb-6">
            Enter the email linked to your Biznie account and we&apos;ll send you a reset link.
          </p>

          {sent ? (
            <div className="space-y-5">
              <div className="rounded-lg bg-green-50 border border-green-100 px-4 py-3 text-sm text-green-700 flex gap-2">
                <Mail size={16} className="mt-0.5 shrink-0" />
                <span>
                  If an account exists for <strong>{email}</strong>, a reset link has been sent. The link expires in 60 minutes.
                </span>
              </div>
              <Link
                href="/login"
                className="inline-flex items-center gap-1.5 text-sm font-semibold text-[#CC1414] hover:underline"
              >
                <ArrowLeft size={14} /> Back to login
              </Link>
            </div>
          ) : (
            <form onSubmit={onSubmit} className="space-y-4" noValidate>
              {error && (
                <div className="rounded-lg bg-red-50 border border-red-100 px-4 py-2 text-sm text-red-700">
                  {error}
                </div>
              )}

              <div>
                <label className="block text-xs font-semibold text-gray-500 mb-1.5 uppercase tracking-wide">Email</label>
                <input
                  required
                  type="email"
                  autoComplete="email"
                  placeholder="you@example.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className={inputClass}
                />
                {fieldError && <p className="text-xs text-red-500 mt-1">{fieldError}</p>}
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full bg-[#CC1414] hover:bg-[#A50E0E] disabled:opacity-70 text-white font-bold py-3.5 rounded-xl transition-colors text-sm flex items-center justify-center gap-2 shadow-md mt-2"
              >
                {loading ? (
                  <>
                    <Loader2 size={16} className="animate-spin" /> Sending...
                  </>
                ) : (
                  "Send reset link"
                )}
              </button>

              <Link
                href="/login"
                className="mt-2 inline-flex items-center gap-1.5 text-sm font-semibold text-gray-500 hover:text-[#CC1414]"
              >
                <ArrowLeft size={14} /> Back to login
              </Link>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}
