"use client"

import { useState } from "react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
  Field,
  FieldDescription,
  FieldGroup,
  FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { authApi } from "@/lib/api/auth.api"
import { toast } from "sonner"
import { useRouter } from "next/navigation"

export function FindIdForm({
  className,
  ...props
}: React.ComponentProps<"form">) {
  const router = useRouter()
  const [step, setStep] = useState<"email" | "verify" | "result">("email")
  const [userName, setUserName] = useState("")
  const [userEmail, setUserEmail] = useState("")
  const [code, setCode] = useState("")
  const [foundUserId, setFoundUserId] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [timer, setTimer] = useState(0)

  // 인증번호 발송
  const handleSendCode = async (e: React.FormEvent) => {
    e.preventDefault()
    console.log(' [아이디 찾기] 인증번호 발송 시도')
    console.log('  - userName:', userName)
    console.log('  - userEmail:', userEmail)

    if (!userName || !userEmail) {
      toast.error("이름과 이메일을 모두 입력해주세요")
      return
    }

    setIsLoading(true)
    try {
      console.log(' API 호출:', { userName, userEmail })
      const result = await authApi.sendFindIdCode(userName, userEmail)
      console.log(' API 응답:', result)
      toast.success(result.message)
      setStep("verify")
      setTimer(result.expiresIn) // (180초 = 3분) 제한 시간 설정========================

      // 타이머 시작
      const interval = setInterval(() => {
        setTimer((prev) => {
          if (prev <= 1) {
            clearInterval(interval)
            return 0
          }
          return prev - 1
        })
      }, 1000)
    } catch (error: any) {
      console.error(' API 에러:', error)
      toast.error(error.message || "인증번호 발송에 실패했습니다")
    } finally {
      setIsLoading(false)
    }
  }

  // 인증번호 확인
  const handleVerifyCode = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!code) {
      toast.error("인증번호를 입력해주세요")
      return
    }

    setIsLoading(true)
    try {
      const result = await authApi.verifyFindIdCode(userEmail, code)
      toast.success(result.message)
      setFoundUserId(result.maskedUserId || result.userId)
      setStep("result")
    } catch (error: any) {
      toast.error(error.message || "인증번호 확인에 실패했습니다")
    } finally {
      setIsLoading(false)
    }
  }

  // 로그인 페이지로 이동
  const handleGoToLogin = () => {
    router.push("/login")
  }

  // 타이머 포맷 (mm:ss)
  const formatTime = (seconds: number) => {
    const m = Math.floor(seconds / 60)
    const s = seconds % 60
    return `${m}:${s.toString().padStart(2, "0")}`
  }

  return (
    <form className={cn("flex flex-col gap-6", className)} {...props}>
      <FieldGroup>
        <div className="flex flex-col items-center gap-1 text-center">
          <h1 className="text-2xl font-bold">아이디 찾기</h1>
          <p className="text-muted-foreground text-sm text-balance">
            {step === "email" && "가입 시 등록한 이름과 이메일을 입력해주세요"}
            {step === "verify" && "이메일로 전송된 인증번호를 입력해주세요"}
            {step === "result" && "아이디 찾기가 완료되었습니다"}
          </p>
        </div>

        {step === "email" && (
          <>
            <Field>
              <FieldLabel htmlFor="name">이름</FieldLabel>
              <Input
                id="name"
                type="text"
                placeholder="홍길동"
                value={userName}
                onChange={(e) => setUserName(e.target.value)}
                required
                disabled={isLoading}
              />
            </Field>
            <Field>
              <FieldLabel htmlFor="email">이메일</FieldLabel>
              <Input
                id="email"
                type="email"
                placeholder="이메일 주소를 입력해주세요"
                value={userEmail}
                onChange={(e) => setUserEmail(e.target.value)}
                required
                disabled={isLoading}
              />
              <FieldDescription>
                가입 시 등록한 이메일 주소를 입력해주세요
              </FieldDescription>
            </Field>
            <Field>
              <Button type="submit" onClick={handleSendCode} disabled={isLoading}>
                {isLoading ? "발송 중..." : "인증번호 발송"}
              </Button>
            </Field>
          </>
        )}

        {step === "verify" && (
          <>
            <Field>
              <FieldLabel htmlFor="email">이메일</FieldLabel>
              <Input
                id="email"
                type="email"
                value={userEmail}
                disabled
              />
            </Field>
            <Field>
              <FieldLabel htmlFor="code">인증번호</FieldLabel>
              <Input
                id="code"
                type="text"
                placeholder="6자리 인증번호"
                value={code}
                onChange={(e) => setCode(e.target.value)}
                maxLength={6}
                required
                disabled={isLoading}
              />
              <FieldDescription>
                {timer > 0 ? `남은 시간: ${formatTime(timer)}` : "인증번호가 만료되었습니다"}
              </FieldDescription>
            </Field>
            <Field>
              <Button type="submit" onClick={handleVerifyCode} disabled={isLoading || timer === 0}>
                {isLoading ? "확인 중..." : "인증번호 확인"}
              </Button>
            </Field>
            <Field>
              <Button type="button" variant="outline" onClick={() => setStep("email")} disabled={isLoading}>
                이메일 다시 입력
              </Button>
            </Field>
          </>
        )}

        {step === "result" && (
          <>
            <Field>
              <div className="bg-muted rounded-lg p-6 text-center">
                <p className="text-sm text-muted-foreground mb-2">회원님의 아이디는</p>
                <p className="text-2xl font-bold text-primary">{foundUserId}</p>
                <p className="text-sm text-muted-foreground mt-2">입니다</p>
              </div>
            </Field>
            <Field>
              <Button type="button" onClick={handleGoToLogin}>
                로그인하러 가기
              </Button>
            </Field>
            <Field>
              <Button type="button" variant="outline" onClick={() => router.push("/findpw")}>
                비밀번호 찾기
              </Button>
            </Field>
          </>
        )}

        <Field>
          <FieldDescription className="px-6 text-center">
            계정이 없으신가요? <a href="/register" className="underline">회원 가입</a>
          </FieldDescription>
        </Field>
      </FieldGroup>
    </form>
  )
}
