"use client";

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";
import { updatePassword } from "@/features/auth/actions";
import {
  resetPasswordSchema,
  type ResetPasswordFormData,
} from "@/features/auth/schemas/auth-schema";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { InlineSpinner } from "@/components/ui/loading-spinner";
import { useState } from "react";

const DEFAULT_ERROR_MESSAGE =
  "알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.";

export default function ResetPasswordForm() {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);
  const [serverError, setServerError] = useState("");

  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
  } = useForm<ResetPasswordFormData>({
    resolver: zodResolver(resetPasswordSchema),
    mode: "onBlur",
  });

  const password = watch("password");
  const confirmPassword = watch("confirmPassword");

  const onSubmit = async (data: ResetPasswordFormData) => {
    setServerError("");
    setIsLoading(true);

    try {
      const formData = new FormData();
      formData.append("password", data.password);

      const result = await updatePassword(formData);

      if (result?.ok) {
        const message = encodeURIComponent(result.message);
        router.replace(`/login?message=${message}`);
        return;
      }

      setServerError(result?.message || DEFAULT_ERROR_MESSAGE);
    } catch (error) {
      console.error("Password reset error:", error);
      setServerError(DEFAULT_ERROR_MESSAGE);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <form className="space-y-5" onSubmit={handleSubmit(onSubmit)}>
      {serverError && (
        <div className="rounded-md bg-red-50 p-3 text-sm text-red-700 dark:bg-red-900/50 dark:text-red-200">
          {serverError}
        </div>
      )}

      <div className="space-y-2">
        <Label htmlFor="password" className="text-sm font-medium">
          새 비밀번호
        </Label>
        <Input
          id="password"
          type="password"
          placeholder="새 비밀번호를 입력해주세요"
          autoComplete="new-password"
          disabled={isLoading}
          {...register("password")}
          className="h-11 transition-all duration-200"
        />
        <p className="text-xs text-gray-500 dark:text-gray-400">
          8자 이상, 대문자/소문자/숫자/특수문자를 각 1개 이상 포함해야 합니다.
        </p>
        {errors.password && (
          <p className="text-xs text-red-600 dark:text-red-400">
            {errors.password.message}
          </p>
        )}
      </div>

      <div className="space-y-2">
        <Label htmlFor="confirmPassword" className="text-sm font-medium">
          새 비밀번호 확인
        </Label>
        <Input
          id="confirmPassword"
          type="password"
          placeholder="새 비밀번호를 다시 입력해주세요"
          autoComplete="new-password"
          disabled={isLoading}
          {...register("confirmPassword")}
          className="h-11 transition-all duration-200"
        />
        {confirmPassword &&
          password !== confirmPassword &&
          !errors.confirmPassword && (
            <p className="text-xs text-red-600 dark:text-red-400">
              비밀번호가 일치하지 않습니다.
            </p>
          )}
        {confirmPassword &&
          password === confirmPassword &&
          !errors.confirmPassword && (
            <p className="text-xs text-green-600 dark:text-green-400">
              비밀번호가 일치합니다.
            </p>
          )}
        {errors.confirmPassword && (
          <p className="text-xs text-red-600 dark:text-red-400">
            {errors.confirmPassword.message}
          </p>
        )}
      </div>

      <Button
        type="submit"
        disabled={isLoading}
        className="h-11 w-full bg-linear-to-r from-gray-900 to-black font-semibold text-white shadow-lg transition-all hover:from-black hover:to-gray-800 hover:shadow-xl dark:from-white dark:to-gray-100 dark:text-black dark:hover:from-gray-100 dark:hover:to-white"
      >
        {isLoading ? (
          <span className="flex items-center gap-2">
            <InlineSpinner />
            변경 중...
          </span>
        ) : (
          "비밀번호 변경"
        )}
      </Button>
    </form>
  );
}
