"use client";

import { useState, FormEvent } from "react";
import { useRouter } from "next/navigation";
import { KeyRound, Mail } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { AuthFormWrapper } from "@/components/auth/auth-form-wrapper";
import { useForgotPassword } from "@/lib/api/hooks/useAuth";
import { ApiRequestError } from "@/lib/api";
import { ROUTES } from "@/lib/constants";

export default function ForgotPasswordPage() {
  const router = useRouter();
  const forgotPassword = useForgotPassword();

  const [email, setEmail] = useState("");
  const [error, setError] = useState("");

  function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setError("");

    if (!email) {
      setError("Email is required");
      return;
    }

    forgotPassword.mutate(
      { email },
      {
        onSuccess: () => {
          router.push(`${ROUTES.RESET_PASSWORD}?email=${encodeURIComponent(email)}`);
        },
        onError: (err) => {
          if (err instanceof ApiRequestError) {
            setError(err.message);
          } else {
            setError("Something went wrong. Please try again.");
          }
        },
      }
    );
  }

  return (
    <AuthFormWrapper
      icon={KeyRound}
      title="Forgot Password"
      subtitle="Enter your email to receive a reset OTP"
      backLabel="Back to login"
      onBack={() => router.push(ROUTES.LOGIN)}
    >
      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="space-y-2">
          <Label htmlFor="email" className="text-gray-300">Email Address</Label>
          <div className="relative">
            <Mail className="absolute left-4 top-1/2 -translate-y-1/2 size-5 text-gray-400" />
            <Input
              id="email"
              type="email"
              placeholder="admin@example.com"
              value={email}
              onChange={(e) => { setEmail(e.target.value); setError(""); }}
              className={`pl-12 bg-gray-800 border-gray-700 text-white placeholder:text-gray-500 ${error ? "border-red-500" : ""}`}
            />
          </div>
          {error && <p className="text-red-400 text-sm mt-1">{error}</p>}
        </div>

        <Button type="submit" disabled={forgotPassword.isPending} className="w-full text-lg py-6">
          {forgotPassword.isPending ? "Sending OTP..." : "Send Reset OTP"}
        </Button>
      </form>
    </AuthFormWrapper>
  );
}
