"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"
import { Eye, EyeOff } from "lucide-react"

export function FindPwForm({
  className,
  ...props
}: React.ComponentProps<"form">) {
  const router = useRouter()
  const [step, setStep] = useState<"info" | "verify" | "reset" | "complete">("info")
  const [userId, setUserId] = useState("")
  const [userEmail, setUserEmail] = useState("")
  const [code, setCode] = useState("")
  const [resetToken, setResetToken] = useState("")
  const [newPassword, setNewPassword] = useState("")
  const [confirmPassword, setConfirmPassword] = useState("")
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [timer, setTimer] = useState(0)

  // 인증번호 발송
  const handleSendCode = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!userId || !userEmail) {
      toast.error("아이디와 이메일을 모두 입력해주세요")
      return
    }

    setIsLoading(true)
    try {
      const result = await authApi.sendResetPasswordCode(userId, 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.verifyResetPasswordCode(userId, userEmail, code)
      toast.success(result.message)
      setResetToken(result.resetToken)
      setStep("reset")
    } catch (error: any) {
      toast.error(error.message || "인증번호 확인에 실패했습니다")
    } finally {
      setIsLoading(false)
    }
  }

  // 비밀번호 재설정
  const handleResetPassword = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!newPassword || !confirmPassword) {
      toast.error("비밀번호를 입력해주세요")
      return
    }

    if (newPassword !== confirmPassword) {
      toast.error("비밀번호가 일치하지 않습니다")
      return
    }

    if (newPassword.length < 8) {
      toast.error("비밀번호는 8자 이상이어야 합니다")
      return
    }

    setIsLoading(true)
    try {
      const result = await authApi.resetPassword(resetToken, newPassword)
      toast.success(result.message)
      setStep("complete")
    } 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}:${s.toString().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 === "info" && "등록된 정보를 입력해주세요"}
            {step === "verify" && "이메일로 전송된 인증번호를 입력해주세요"}
            {step === "reset" && "새로운 비밀번호를 설정해주세요"}
            {step === "complete" && "비밀번호 재설정이 완료되었습니다"}
          </p>
        </div>

        {step === "info" && (
          <>
            <Field>
              <FieldLabel htmlFor="userId" className="text-sm lg:text-base">아이디</FieldLabel>
              <Input
                id="userId"
                type="text"
                placeholder="아이디를 입력하세요"
                value={userId}
                onChange={(e) => setUserId(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="/findid" 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="userId" className="text-sm lg:text-base">아이디</FieldLabel>
              <Input id="userId" type="text" value={userId} disabled className="h-10 lg:h-11" />
            </Field>
            <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("info")} disabled={isLoading} className="w-full h-10 lg:h-11">
                정보 다시 입력
              </Button>
            </Field>
          </>
        )}

        {step === "reset" && (
          <>
            <Field>
              <FieldLabel htmlFor="newPassword" className="text-sm lg:text-base">새 비밀번호</FieldLabel>
              <div className="relative">
                <Input
                  id="newPassword"
                  type={showPassword ? "text" : "password"}
                  placeholder="8자 이상 입력하세요"
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  required
                  disabled={isLoading}
                  className="h-10 lg:h-11 pr-10"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  tabIndex={-1}
                >
                  {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </Field>
            <Field>
              <FieldLabel htmlFor="confirmPassword" className="text-sm lg:text-base">비밀번호 확인</FieldLabel>
              <div className="relative">
                <Input
                  id="confirmPassword"
                  type={showConfirmPassword ? "text" : "password"}
                  placeholder="비밀번호를 다시 입력하세요"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  required
                  disabled={isLoading}
                  className="h-10 lg:h-11 pr-10"
                />
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  tabIndex={-1}
                >
                  {showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
              {newPassword && confirmPassword && newPassword !== confirmPassword && (
                <FieldDescription className="text-destructive">
                  비밀번호가 일치하지 않습니다
                </FieldDescription>
              )}
            </Field>
            <Field>
              <Button type="submit" onClick={handleResetPassword} disabled={isLoading} className="w-full h-10 lg:h-11">
                {isLoading ? "변경 중..." : "비밀번호 변경"}
              </Button>
            </Field>
          </>
        )}

        {step === "complete" && (
          <>
            <Field>
              <div className="bg-muted rounded-lg p-4 lg:p-6 text-center">
                <p className="text-base lg:text-lg font-semibold text-primary mb-2">비밀번호 재설정 완료</p>
                <p className="text-xs lg:text-sm text-muted-foreground">
                  새로운 비밀번호로 로그인해주세요
                </p>
              </div>
            </Field>
            <Field>
              <Button type="button" onClick={() => router.push("/login")} className="w-full h-10 lg:h-11">
                로그인하러 가기
              </Button>
            </Field>
          </>
        )}

        {step === "info" && (
          <>
            <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>
  )
}
