"use client"

import { useState } from "react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
  Field,
  FieldDescription,
  FieldGroup,
  FieldLabel,
  FieldSeparator,
} 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()

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

    setIsLoading(true)
    try {
      const result = await authApi.sendFindIdCode(userName, userEmail)
      toast.success(result.message)
      setStep("verify")
      setTimer(result.expiresIn)

      const interval = setInterval(() => {
        setTimer((prev) => {
          if (prev <= 1) {
            clearInterval(interval)
            return 0
          }
          return prev - 1
        })
      }, 1000)
    } catch (error: any) {
      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 formatTime = (seconds: number) => {
    const m = Math.floor(seconds / 60)
    const s = seconds % 60
    return m + ":" + String(s).padStart(2, "0")
  }

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

        {step === "email" && (
          <>
            <Field>
              <FieldLabel htmlFor="name" className="text-sm lg:text-base">이름</FieldLabel>
              <Input
                id="name"
                type="text"
                placeholder="이름을 입력하세요"
                value={userName}
                onChange={(e) => setUserName(e.target.value)}
                required
                disabled={isLoading}
                className="h-10 lg:h-11"
              />
            </Field>
            <Field>
              <div className="flex items-center justify-between">
                <FieldLabel htmlFor="email" className="text-sm lg:text-base">이메일</FieldLabel>
                <a href="/findpw" className="text-xs text-primary hover:underline">
                  비밀번호 찾기
                </a>
              </div>
              <Input
                id="email"
                type="email"
                placeholder="이메일을 입력하세요"
                value={userEmail}
                onChange={(e) => setUserEmail(e.target.value)}
                required
                disabled={isLoading}
                className="h-10 lg:h-11"
              />
            </Field>
            <Field>
              <Button type="submit" onClick={handleSendCode} disabled={isLoading} className="w-full h-10 lg:h-11">
                {isLoading ? "발송 중..." : "인증번호 발송"}
              </Button>
            </Field>
          </>
        )}

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

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

        {step === "email" && (
          <>
            <FieldSeparator>또는</FieldSeparator>
            <Field>
              <Button
                variant="outline"
                type="button"
                onClick={() => router.push("/login")}
                className="w-full h-10 lg:h-11 border-2 border-primary text-primary hover:bg-primary hover:text-primary-foreground hover:border-transparent transition-all duration-300"
              >
                로그인
              </Button>
            </Field>
            <div className="text-center">
              <a href="/signup" className="text-xs lg:text-sm text-gray-500 hover:text-primary">
                계정이 없으신가요? 회원가입
              </a>
            </div>
          </>
        )}
      </FieldGroup>
    </form>
  )
}
