"use client";

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
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";

/**
 * [비밀번호 재설정 폼 클라이언트 컴포넌트 - React Hook Form 버전]
 *
 * React Hook Form과 Zod를 사용한 비밀번호 재설정 폼입니다.
 * - 타입 안전한 폼 검증
 * - 비밀번호/비밀번호 확인 일치 검증
 * - 로딩 상태 표시
 *
 * @see app/reset-password/page.tsx - 이 컴포넌트를 사용하는 페이지
 */
export default function ResetPasswordForm() {
  // ========== 로딩 상태 ==========
  const [isLoading, setIsLoading] = useState(false);
  const [serverError, setServerError] = useState("");

  // ========== React Hook Form 설정 ==========
  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);

      await updatePassword(formData);
    } catch (error) {
      console.error("Password reset error:", error);
      setServerError("비밀번호 변경 중 오류가 발생했습니다.");
    } 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자 이상, 대문자, 소문자, 숫자, 특수문자 포함
        </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>
          )}
        {/* Zod 검증 에러 */}
        {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-gradient-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>
  );
}
