'use client'

import { useState, Suspense } from 'react'
import Link from 'next/link'
import { useRouter, useSearchParams } from 'next/navigation'

function ResetPasswordContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const token = searchParams.get('token')
  
  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (password !== confirmPassword) {
      setError('Password tidak cocok')
      return
    }
    if (password.length < 8) {
      setError('Password minimal 8 karakter')
      return
    }

    setLoading(true)
    setError('')

    try {
      const res = await fetch('/api/auth/reset-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token, password }),
      })
      const data = await res.json()
      
      if (!res.ok) throw new Error(data.error || 'Terjadi kesalahan')
      
      setSuccess(true)
    } catch (err: any) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  if (!token) {
    return (
      <div style={{ textAlign: 'center', padding: '40px', color: '#ef4444' }}>
        Token tidak valid. Silakan ulangi proses lupa password.
        <br/><br/>
        <Link href="/auth/forgot-password" style={{ color: '#f59e0b' }}>Kembali</Link>
      </div>
    )
  }

  return (
    <div style={{ width: '100%', maxWidth: '420px', position: 'relative', zIndex: 1 }}>
      <div style={{ textAlign: 'center', marginBottom: '40px' }}>
        <h1 style={{ fontSize: '24px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>
          Reset Password
        </h1>
        <p style={{ color: '#64748b', fontSize: '14px' }}>
          Masukkan password baru Anda.
        </p>
      </div>

      <div className="card" style={{ padding: '32px' }}>
        {success ? (
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '48px', marginBottom: '16px' }}>✅</div>
            <h3 style={{ color: '#10b981', marginBottom: '8px' }}>Password Berhasil Diubah</h3>
            <p style={{ color: '#94a3b8', fontSize: '14px', marginBottom: '24px' }}>
              Silakan login dengan password baru Anda.
            </p>
            <Link href="/auth/login" className="btn btn-primary" style={{ display: 'block', padding: '12px' }}>
              Ke Halaman Login
            </Link>
          </div>
        ) : (
          <form onSubmit={handleSubmit}>
            {error && (
              <div style={{ padding: '12px', background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.2)', borderRadius: '8px', color: '#ef4444', fontSize: '13px', marginBottom: '16px' }}>
                ❌ {error}
              </div>
            )}

            <div style={{ marginBottom: '16px' }}>
              <label className="label">Password Baru</label>
              <input
                className="input"
                type="password"
                placeholder="Minimal 8 karakter"
                value={password}
                onChange={e => setPassword(e.target.value)}
                required
              />
            </div>
            
            <div style={{ marginBottom: '24px' }}>
              <label className="label">Konfirmasi Password Baru</label>
              <input
                className="input"
                type="password"
                placeholder="Ulangi password baru"
                value={confirmPassword}
                onChange={e => setConfirmPassword(e.target.value)}
                required
              />
            </div>

            <button
              type="submit"
              className="btn btn-primary"
              style={{ width: '100%', padding: '13px', fontSize: '15px' }}
              disabled={loading || !password || !confirmPassword}
            >
              {loading ? <><span className="spinner" /> Menyimpan...</> : 'Simpan Password Baru'}
            </button>
          </form>
        )}
      </div>
    </div>
  )
}

export default function ResetPasswordPage() {
  return (
    <main style={{
      minHeight: '100vh',
      background: '#0a0a0f',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '24px',
    }}>
      <div style={{
        position: 'fixed', top: '20%', left: '30%',
        width: 400, height: 400,
        background: 'radial-gradient(circle, rgba(245,158,11,0.06), transparent 70%)',
        borderRadius: '50%', pointerEvents: 'none',
      }} />
      <Suspense fallback={<span className="spinner" />}>
        <ResetPasswordContent />
      </Suspense>
    </main>
  )
}
