"use client";

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { signup } from "@/features/auth/actions";
import {
  signupSchema,
  type SignupFormData,
} 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/signup/page.tsx - 이 컴포넌트를 사용하는 페이지
 */
export default function SignupForm() {
  // ========== 로딩 상태 ==========
  const [isLoading, setIsLoading] = useState(false);
  const [serverError, setServerError] = useState("");

  // ========== React Hook Form 설정 ==========
  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
  } = useForm<SignupFormData>({
    resolver: zodResolver(signupSchema),
    mode: "onBlur", // 포커스 아웃 시 검증
  });

  // 비밀번호 실시간 감시 (일치 여부 표시용)
  const password = watch("password");
  const confirmPassword = watch("confirmPassword");

  // ========== 폼 제출 핸들러 ==========
  const onSubmit = async (data: SignupFormData) => {
    setServerError("");
    setIsLoading(true);

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

      await signup(formData);
    } catch (error) {
      console.error("Signup 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="email" className="text-sm font-medium">
          이메일
        </Label>
        <Input
          id="email"
          type="email"
          placeholder="your@email.com"
          autoComplete="email"
          disabled={isLoading}
          {...register("email")}
          className="h-11 transition-all duration-200 focus-visible:ring-brand-500"
        />
        {errors.email && (
          <p className="text-xs text-red-600 dark:text-red-400">
            {errors.email.message}
          </p>
        )}
      </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 focus-visible:ring-brand-500"
        />
        <p className="text-xs text-muted-foreground">
          최소 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 focus-visible:ring-brand-500"
        />
        {/* 비밀번호 불일치 시 실시간 피드백 */}
        {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-brand-600 dark:text-brand-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-linear-to-r from-brand-500 to-brand-700 font-semibold text-white shadow-lg shadow-brand-500/20 transition-all duration-200 hover:from-brand-600 hover:to-brand-800 hover:shadow-xl hover:shadow-brand-500/25"
      >
        {isLoading ? (
          <span className="flex items-center gap-2">
            <InlineSpinner />
            회원가입 중...
          </span>
        ) : (
          "회원가입 완료"
        )}
      </Button>
    </form>
  );
}
