"use client";

import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { resetPasswordWithOTP } from "@/lib/actions/auth";

export function ResetForm({ defaultEmail }: { defaultEmail: string }) {
  const t = useTranslations("Auth.resetPassword");
  const router = useRouter();
  const [email, setEmail] = useState(defaultEmail);
  const [otp, setOtp] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [isPending, startTransition] = useTransition();

  function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    if (newPassword !== confirmPassword) {
      toast.error(t("passwordMismatch"));
      return;
    }
    if (newPassword.length < 8) {
      toast.error(t("passwordTooShort"));
      return;
    }
    const trimmedEmail = email.trim();
    const trimmedOtp = otp.trim();
    if (!trimmedEmail || !trimmedOtp || !newPassword) return;
    startTransition(async () => {
      try {
        await resetPasswordWithOTP({
          email: trimmedEmail,
          otp: trimmedOtp,
          newPassword,
        });
        toast.success(t("resetSuccess"));
        router.push("/login");
      } catch {
        toast.error(t("resetFailed"));
      }
    });
  }

  return (
    <form onSubmit={onSubmit} className="flex flex-col gap-3">
      <div className="flex flex-col gap-2">
        <Label htmlFor="reset-email">{t("emailLabel")}</Label>
        <Input
          id="reset-email"
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder={t("emailPlaceholder")}
          required
        />
      </div>
      <div className="flex flex-col gap-2">
        <Label htmlFor="reset-otp">{t("otpLabel")}</Label>
        <Input
          id="reset-otp"
          inputMode="numeric"
          autoComplete="one-time-code"
          value={otp}
          onChange={(e) => setOtp(e.target.value.replace(/\D/g, "").slice(0, 6))}
          placeholder="123456"
          required
          className="text-center text-2xl tracking-[0.4em]"
          maxLength={6}
        />
        <p className="text-xs text-muted-foreground">{t("otpHelper", { email: email || "—" })}</p>
      </div>
      <div className="flex flex-col gap-2">
        <Label htmlFor="reset-new">{t("newPasswordLabel")}</Label>
        <Input
          id="reset-new"
          type="password"
          value={newPassword}
          onChange={(e) => setNewPassword(e.target.value)}
          placeholder={t("newPasswordPlaceholder")}
          required
          minLength={8}
          autoComplete="new-password"
        />
        <p className="text-xs text-muted-foreground">{t("newPasswordHelper")}</p>
      </div>
      <div className="flex flex-col gap-2">
        <Label htmlFor="reset-confirm">{t("confirmPasswordLabel")}</Label>
        <Input
          id="reset-confirm"
          type="password"
          value={confirmPassword}
          onChange={(e) => setConfirmPassword(e.target.value)}
          required
          minLength={8}
          autoComplete="new-password"
        />
      </div>
      <Button
        type="submit"
        disabled={
          isPending ||
          !email.trim() ||
          otp.length < 4 ||
          newPassword.length < 8 ||
          newPassword !== confirmPassword
        }
      >
        {isPending ? t("resetting") : t("submit")}
      </Button>
    </form>
  );
}
