"use client";

import { useState, FormEvent, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { KeyRound, Lock } 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 { useResetPassword, useResendOtp } from "@/lib/api/hooks/useAuth";
import { ApiRequestError } from "@/lib/api";
import { ROUTES } from "@/lib/constants";

function ResetPasswordForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const email = searchParams.get("email") ?? "";

  const resetPassword = useResetPassword();
  const resendOtp = useResendOtp();

  const [otp, setOtp] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState("");
  const [message, setMessage] = useState("");

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

    if (password.length < 8) {
      setError("Password must be at least 8 characters");
      return;
    }
    if (password !== confirmPassword) {
      setError("Passwords do not match");
      return;
    }

    resetPassword.mutate(
      { email, otp, password, confirmPassword },
      {
        onSuccess: () => {
          router.push(ROUTES.LOGIN);
        },
        onError: (err) => {
          if (err instanceof ApiRequestError) {
            setError(err.message);
          } else {
            setError("Something went wrong. Please try again.");
          }
        },
      }
    );
  }

  function handleResend() {
    setError("");
    resendOtp.mutate(
      { email, type: "password-reset" },
      {
        onSuccess: (data) => setMessage(data.message),
        onError: (err) => {
          if (err instanceof ApiRequestError) setError(err.message);
        },
      }
    );
  }

  return (
    <AuthFormWrapper
      icon={KeyRound}
      title="Reset Password"
      subtitle={`Enter the OTP sent to ${email || "your email"} and your new password`}
      backLabel="Back to login"
      onBack={() => router.push(ROUTES.LOGIN)}
    >
      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="space-y-2">
          <Label htmlFor="otp" className="text-gray-300">OTP Code</Label>
          <Input
            id="otp"
            type="text"
            inputMode="numeric"
            placeholder="Enter 6-digit OTP"
            maxLength={6}
            value={otp}
            onChange={(e) => { setOtp(e.target.value); setError(""); }}
            className={`text-center text-lg tracking-widest bg-gray-800 border-gray-700 text-white placeholder:text-gray-500 ${error ? "border-red-500" : ""}`}
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="password" className="text-gray-300">New Password</Label>
          <div className="relative">
            <Lock className="absolute left-4 top-1/2 -translate-y-1/2 size-5 text-gray-400" />
            <Input
              id="password"
              type="password"
              placeholder="New password"
              value={password}
              onChange={(e) => { setPassword(e.target.value); setError(""); }}
              className="pl-12 bg-gray-800 border-gray-700 text-white placeholder:text-gray-500"
            />
          </div>
        </div>

        <div className="space-y-2">
          <Label htmlFor="confirm-password" className="text-gray-300">Confirm Password</Label>
          <div className="relative">
            <Lock className="absolute left-4 top-1/2 -translate-y-1/2 size-5 text-gray-400" />
            <Input
              id="confirm-password"
              type="password"
              placeholder="Confirm new password"
              value={confirmPassword}
              onChange={(e) => { setConfirmPassword(e.target.value); setError(""); }}
              className="pl-12 bg-gray-800 border-gray-700 text-white placeholder:text-gray-500"
            />
          </div>
          {error && <p className="text-red-400 text-sm mt-1">{error}</p>}
          {message && <p className="text-green-400 text-sm mt-1">{message}</p>}
        </div>

        <Button type="submit" disabled={resetPassword.isPending} className="w-full text-lg py-6">
          {resetPassword.isPending ? "Resetting..." : "Reset Password"}
        </Button>

        <button
          type="button"
          onClick={handleResend}
          disabled={resendOtp.isPending}
          className="w-full text-sm text-gray-400 hover:text-white transition-colors"
        >
          {resendOtp.isPending ? "Sending..." : "Didn't receive the code? Resend OTP"}
        </button>
      </form>
    </AuthFormWrapper>
  );
}

export default function ResetPasswordPage() {
  return (
    <Suspense>
      <ResetPasswordForm />
    </Suspense>
  );
}
