'use client';

import Image from "next/image"
import { SignupForm } from "@/components/auth/signup-form"
import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { useAuthStore } from "@/store/auth-store"
import { authApi } from "@/lib/api/auth.api"
import { SignupFormData } from "@/types/auth.types"

export default function SignupPage() {
  const [formData, setFormData] = useState<SignupFormData>({
    userSe: '',
    userId: '',
    userPassword: '',
    confirmPassword: '',
    userName: '',
    userPhone: '',
    userEmail: '',
    emailId: '',
    emailDomain: 'gmail.com',
  })
  const [verificationCode, setVerificationCode] = useState('')
  const [isEmailVerified, setIsEmailVerified] = useState(false)
  const [verifiedEmail, setVerifiedEmail] = useState('')
  const [isSendingCode, setIsSendingCode] = useState(false)
  const [isVerifyingCode, setIsVerifyingCode] = useState(false)
  const [isCodeSent, setIsCodeSent] = useState(false)
  const [error, setError] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [emailCheckStatus, setEmailCheckStatus] = useState<'idle' | 'checking' | 'available' | 'unavailable'>('idle')
  const [emailCheckMessage, setEmailCheckMessage] = useState('')
  const [currentStep, setCurrentStep] = useState(1)
  const router = useRouter()
  const { signup } = useAuthStore()

  useEffect(() => {
    if (formData.userEmail !== verifiedEmail) {
      setIsCodeSent(false)
      setIsEmailVerified(false)
      setVerificationCode('')
    }

    if (!formData.emailId) {
      setEmailCheckStatus('idle')
      setEmailCheckMessage('이메일 아이디를 입력하세요')
      return
    }

    if (!formData.emailDomain || (formData.emailDomain === '직접입력' && !formData.customDomain)) {
      setEmailCheckStatus('idle')
      setEmailCheckMessage('이메일 도메인을 선택하세요')
      return
    }

    if (!formData.userEmail || !formData.userEmail.includes('@')) {
      setEmailCheckStatus('idle')
      setEmailCheckMessage('')
      return
    }

    if (formData.userEmail === verifiedEmail && isEmailVerified) {
      return
    }

    const timer = setTimeout(async () => {
      setEmailCheckStatus('checking')
      setEmailCheckMessage('이메일 확인 중...')

      try {
        const result = await authApi.checkEmail(formData.userEmail)
        if (result.available) {
          setEmailCheckStatus('available')
          setEmailCheckMessage(result.message)
        } else {
          setEmailCheckStatus('unavailable')
          setEmailCheckMessage(result.message)
        }
      } catch (err: unknown) {
        setEmailCheckStatus('idle')
        setEmailCheckMessage('')
      }
    }, 500)

    return () => clearTimeout(timer)
  }, [formData.emailId, formData.emailDomain, formData.customDomain, formData.userEmail, verifiedEmail, isEmailVerified])

  const handleSendVerificationCode = async () => {
    if (!formData.userEmail) {
      setError('이메일을 입력해주세요.')
      return
    }

    setError('')
    setIsSendingCode(true)

    try {
      const response = await authApi.sendSignupCode(formData.userEmail)
      const expiryMinutes = Math.floor((response.expiresIn || 180) / 60)
      setIsCodeSent(true)
      alert(`인증번호가 이메일로 발송되었습니다. (유효시간: ${expiryMinutes}분)`)
    } catch (err: unknown) {
      if (err instanceof Error) {
        setError(err.message)
      } else {
        setError('인증번호 발송에 실패했습니다.')
      }
    } finally {
      setIsSendingCode(false)
    }
  }

  const handleVerifyCode = async () => {
    if (!verificationCode) {
      setError('인증번호를 입력해주세요.')
      return
    }

    setError('')
    setIsVerifyingCode(true)

    try {
      const response = await authApi.verifySignupCode(formData.userEmail, verificationCode)
      if (response.verified) {
        setIsEmailVerified(true)
        setVerifiedEmail(formData.userEmail)
        alert('이메일 인증이 완료되었습니다!')
      } else {
        setError('인증번호가 일치하지 않습니다.')
      }
    } catch (err: unknown) {
      if (err instanceof Error) {
        setError(err.message)
      } else {
        setError('인증번호 확인에 실패했습니다.')
      }
    } finally {
      setIsVerifyingCode(false)
    }
  }

  const handleSignup = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')

    if (!formData.userSe) {
      setError('회원 유형을 선택해주세요.')
      return
    }

    if (formData.userId.length < 4) {
      setError('아이디는 4자 이상이어야 합니다.')
      return
    }

    if (formData.userName.length < 2) {
      setError('이름은 2자 이상이어야 합니다.')
      return
    }

    if (!isEmailVerified) {
      setError('이메일 인증을 완료해주세요.')
      return
    }

    if (formData.userPassword.length < 8) {
      setError('비밀번호는 8자 이상이어야 합니다.')
      return
    }

    if (formData.userPassword !== formData.confirmPassword) {
      setError('비밀번호가 일치하지 않습니다.')
      return
    }

    if (formData.userSe !== 'FARM' && !formData.userInstName) {
      setError('컨설턴트/기관 회원은 기관명이 필수입니다.')
      return
    }

    setIsLoading(true)

    try {
      await signup({
        userSe: formData.userSe as 'FARM' | 'CNSLT' | 'ORGAN',
        userId: formData.userId,
        userPassword: formData.userPassword,
        userName: formData.userName,
        userPhone: formData.userPhone,
        userEmail: formData.userEmail,
        userInstName: formData.userInstName || undefined,
        userBirth: formData.userBirth || undefined,
        userAddress: formData.userAddress || undefined,
        userBizNo: formData.userBizNo || undefined,
      })

      alert('회원가입이 완료되었습니다!')
      router.push('/login')
    } catch (err: unknown) {
      if (err instanceof Error) {
        setError(err.message)
      } else {
        setError('알 수 없는 오류가 발생했습니다')
      }
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="grid min-h-svh lg:grid-cols-2">
      {/* 데스크톱: 왼쪽 로고 이미지 영역 */}
      <div className="bg-white relative hidden lg:flex items-center justify-center">
        <Image
          src="/logo-graphic.svg"
          alt="한우 유전체 컨설팅 로고"
          fill
          className="object-contain p-16 -translate-y-12 translate-x-24"
          priority
        />
      </div>

      {/* 오른쪽 폼 영역 */}
      <div className="flex flex-col p-4 md:p-10 bg-white">
        {/* 로고 + 폼을 하나로 묶어서 중앙 정렬 */}
        <div className="flex flex-1 items-center justify-center lg:justify-start lg:pl-16">
          <div className="w-full max-w-[300px] lg:max-w-sm">
            {/* 모바일: 로고 - 폼 바로 위에 붙어있음 */}
            <div className="lg:hidden flex justify-center mb-2">
              <Image
                src="/logo-graphic.svg"
                alt="한우 유전체 컨설팅 로고"
                width={120}
                height={120}
                className="object-contain"
                priority
              />
            </div>
            <SignupForm
              onSubmit={handleSignup}
              formData={formData}
              setFormData={setFormData}
              error={error}
              isLoading={isLoading}
              onSendVerificationCode={handleSendVerificationCode}
              isEmailVerified={isEmailVerified}
              isSendingCode={isSendingCode}
              isCodeSent={isCodeSent}
              verificationCode={verificationCode}
              setVerificationCode={setVerificationCode}
              onVerifyCode={handleVerifyCode}
              isVerifyingCode={isVerifyingCode}
              emailCheckStatus={emailCheckStatus}
              emailCheckMessage={emailCheckMessage}
              currentStep={currentStep}
              setCurrentStep={setCurrentStep}
            />
          </div>
        </div>
      </div>
    </div>
  )
}
