﻿"use client";

import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  forgotPasswordSchema,
  type ForgotPasswordInput,
} from "@/lib/validations/auth";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import { Loader2, Mail } from "lucide-react";
import { useRouter } from "next/navigation";
import { clientRateLimit } from "@/core/security/rate-limit";
import {
  generateClientCsrfToken,
  verifyClientCsrfToken,
} from "@/core/security/client-csrf";
import { sanitizeEmail } from "@/core/security/sanitize";
import { initiatePasswordResetAction } from "@/features/auth/actions/auth-actions";

export function ForgetPasswordForm() {
  const [isLoading, setIsLoading] = useState(false);
  const [csrfToken, setCsrfToken] = useState<string>("");
  const toast = useToastEnhanced();
  const router = useRouter();

  useEffect(() => {
    setCsrfToken(generateClientCsrfToken());
  }, []);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<ForgotPasswordInput>({
    resolver: zodResolver(forgotPasswordSchema),
  });

  const onSubmit = async (data: ForgotPasswordInput) => {
    if (!verifyClientCsrfToken(csrfToken)) {
      toast.error({
        title: "Security error",
        description: "Please refresh the page and try again",
      });
      return;
    }

    const rateCheck = clientRateLimit("password_reset", 3, 300000); // 3 attempts per 5 minutes
    if (!rateCheck.allowed) {
      const waitTime = Math.ceil(rateCheck.resetIn / 60000);
      toast.error({
        title: "Too many attempts",
        description: `Please wait ${waitTime} minute(s) before trying again`,
      });
      return;
    }

    setIsLoading(true);

    try {
      const sanitizedEmail = sanitizeEmail(data.email);

      const result = await initiatePasswordResetAction(sanitizedEmail);

      if (!result.success) {
        throw new Error(result.error || "Failed to send verification code");
      }

      toast.success({
        title: "Verification code sent",
        description: "Please check your email for the verification code",
        duration: 5000,
      });

      // Redirect to OTP verification page
      router.push("/otp-verification");
    } catch (error) {
      toast.error({
        title: "Failed to send code",
        description:
          error instanceof Error ? error.message : "Please try again",
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-5">
      <input type="hidden" name="csrf_token" value={csrfToken} />

      <div className="space-y-2">
        <Label htmlFor="forget-email">Email address</Label>
        <div className="relative">
          <Mail
            className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"
            aria-hidden="true"
          />
          <Input
            id="forget-email"
            type="email"
            placeholder="your@email.com"
            autoComplete="email"
            disabled={isLoading}
            className="pl-10"
            aria-invalid={errors.email ? "true" : "false"}
            aria-describedby={errors.email ? "forget-email-error" : undefined}
            {...register("email")}
          />
        </div>
        {errors.email && (
          <p
            id="forget-email-error"
            className="text-sm text-destructive"
            role="alert"
          >
            {errors.email.message}
          </p>
        )}
      </div>

      <Button
        type="submit"
        className="w-full"
        size="lg"
        disabled={isLoading}
        aria-label="Send verification code"
      >
        {isLoading && (
          <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />
        )}
        {isLoading ? "Sending code..." : "Send Verification Code"}
      </Button>
    </form>
  );
}
