"use client"
import { useState, useEffect } from 'react'
import Link from 'next/link'
import { useSearchParams, useRouter } from 'next/navigation'

export default function LoginPage(){
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const search = useSearchParams()
  const router = useRouter()
  const redirect = search.get('redirect') || '/dashboard'
  const [alertMsg, setAlertMsg] = useState('')

  useEffect(()=>{
    if(search.get('redirect')){
      // 요구사항: 비로그인 접근시 alert 후 로그인으로
      setAlertMsg('로그인이 필요한 페이지입니다.')
    }
  },[search])

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError('')
    try{
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers:{'Content-Type':'application/json'},
        body: JSON.stringify({ email, password })
      })
      const data = await res.json()
      if(!res.ok) throw new Error(data.error || '로그인 실패')
      router.push(redirect)
    }catch(err:any){
      setError(err.message)
    }finally{
      setLoading(false)
    }
  }

  const googleLoginUrl = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID || ''}&redirect_uri=https://i.yjm.kr/api/auth/google/callback&response_type=code&scope=email profile&access_type=offline&prompt=consent`

  return (
    <div className="min-h-screen bg-slate-50 flex items-center justify-center p-4">
      <div className="w-full max-w-md bg-white rounded-2xl shadow-lg border border-slate-200 p-8">
        <h1 className="text-2xl font-bold text-slate-900">로그인</h1>
        <p className="text-sm text-slate-500 mt-1">ReplyOne에 오신걸 환영합니다</p>

        {alertMsg && <div className="mt-4 bg-amber-50 border border-amber-200 text-amber-800 text-sm p-3 rounded-lg">{alertMsg}</div>}
        {error && <div className="mt-4 bg-red-50 border border-red-200 text-red-700 text-sm p-3 rounded-lg">{error}</div>}

        <form onSubmit={handleLogin} className="mt-6 space-y-4">
          <div>
            <label className="text-sm font-medium text-slate-900">이메일</label>
            <input value={email} onChange={e=>setEmail(e.target.value)} type="email" required placeholder="you@example.com"
              className="mt-1 w-full px-3 py-2.5 rounded-lg border border-slate-300 bg-white text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-slate-900 focus:border-slate-900"/>
          </div>
          <div>
            <label className="text-sm font-medium text-slate-900">비밀번호</label>
            <input value={password} onChange={e=>setPassword(e.target.value)} type="password" required placeholder="••••••••"
              className="mt-1 w-full px-3 py-2.5 rounded-lg border border-slate-300 bg-white text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-slate-900 focus:border-slate-900"/>
          </div>

          <button disabled={loading} type="submit"
            className="w-full bg-slate-900 text-white py-2.5 rounded-lg font-semibold hover:bg-black disabled:opacity-50 disabled:cursor-not-allowed transition">
            {loading ? '로그인 중...' : '로그인'}
          </button>
        </form>

        <div className="mt-6">
          <div className="relative">
            <div className="absolute inset-0 flex items-center"><div className="w-full border-t border-slate-200"/></div>
            <div className="relative flex justify-center text-xs uppercase"><span className="bg-white px-2 text-slate-500">또는</span></div>
          </div>

          <div className="mt-4 grid gap-2">
            <a href="/api/auth/google"
              className="w-full flex items-center justify-center gap-2 border border-slate-300 bg-white text-slate-900 py-2.5 rounded-lg font-medium hover:bg-slate-50 transition">
              <img src="https://www.svgrepo.com/show/475656/google-color.svg" className="w-5 h-5"/> Google로 계속하기
            </a>
            <button disabled className="w-full flex items-center justify-center gap-2 border border-slate-200 bg-slate-50 text-slate-400 py-2.5 rounded-lg font-medium cursor-not-allowed">
              Facebook / Supabase 연동 예정
            </button>
          </div>
        </div>

        <div className="mt-6 flex justify-between text-sm">
          <Link href="/signup" className="text-slate-900 font-medium underline">회원가입</Link>
          <Link href="/forgot-password" className="text-slate-500 hover:text-slate-900">비밀번호 찾기</Link>
        </div>
      </div>
    </div>
  )
}
