import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import { generateFingerprint } from '@/lib/fingerprint'

export default function Register() {
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [instagram, setInstagram] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [fingerprint, setFingerprint] = useState('')
  const router = useRouter()

  useEffect(() => {
    // Generate browser fingerprint on component mount
    const fp = generateFingerprint()
    setFingerprint(fp)
  }, [])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!name.trim() || !email.trim()) {
      setError('Please fill in all required fields')
      return
    }

    setLoading(true)
    setError('')

    try {
      const response = await fetch('/api/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: name.trim(),
          email: email.trim(),
          instagram: instagram.trim(),
          fingerprint: fingerprint
        })
      })

      if (response.ok) {
        const data = await response.json()
        router.push(`/qr/${data.accessCode}`)
      } else {
        const errorData = await response.json()
        
        if (errorData.error === 'DUPLICATE_REGISTRATION') {
          // Show detailed duplicate registration message
          setError(`Anda sudah melakukan registrasi untuk ${errorData.reason}. ${errorData.suggestion}`)
        } else {
          setError(errorData.message || 'Registration failed')
        }
      }
    } catch (error) {
      setError('Network error. Please try again.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div style={{ 
      minHeight: '100vh', 
      display: 'flex', 
      alignItems: 'center', 
      justifyContent: 'center',
      backgroundColor: '#f5f5f5'
    }}>
      <div style={{
        backgroundColor: 'white',
        padding: '40px',
        borderRadius: '8px',
        boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)',
        width: '100%',
        maxWidth: '400px'
      }}>
        <h1 style={{ 
          textAlign: 'center', 
          marginBottom: '30px',
          color: '#333',
          fontSize: '24px'
        }}>
          Pendaftaran Photobooth
        </h1>
        
        <form onSubmit={handleSubmit}>
          <div style={{ marginBottom: '20px' }}>
            <label style={{ 
              display: 'block', 
              marginBottom: '8px',
              fontWeight: 'bold',
              color: '#555'
            }}>
              Nama Lengkap *
            </label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Nama lengkap Anda"
              style={{
                width: '100%',
                padding: '12px',
                border: '1px solid #ddd',
                borderRadius: '4px',
                fontSize: '16px',
                boxSizing: 'border-box'
              }}
              disabled={loading}
            />
          </div>


          <div style={{ marginBottom: '20px' }}>
            <label style={{ 
              display: 'block', 
              marginBottom: '8px',
              fontWeight: 'bold',
              color: '#555'
            }}>
              Email *
            </label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="email@aktif.com"
              style={{
                width: '100%',
                padding: '12px',
                border: '1px solid #ddd',
                borderRadius: '4px',
                fontSize: '16px',
                boxSizing: 'border-box'
              }}
              disabled={loading}
            />
          </div>

          <div style={{ marginBottom: '20px' }}>
            <label style={{ 
              display: 'block', 
              marginBottom: '8px',
              fontWeight: 'bold',
              color: '#555'
            }}>
              Username Instagram
            </label>
            <input
              type="text"
              value={instagram}
              onChange={(e) => setInstagram(e.target.value)}
              placeholder="username Instagram"
              style={{
                width: '100%',
                padding: '12px',
                border: '1px solid #ddd',
                borderRadius: '4px',
                fontSize: '16px',
                boxSizing: 'border-box'
              }}
              disabled={loading}
            />
          </div>

          {error && (
            <div style={{
              backgroundColor: '#ffebee',
              color: '#c62828',
              padding: '12px',
              borderRadius: '4px',
              marginBottom: '20px',
              fontSize: '14px'
            }}>
              {error}
            </div>
          )}

          <button
            type="submit"
            disabled={loading}
            style={{
              width: '100%',
              padding: '12px',
              backgroundColor: loading ? '#ccc' : '#007bff',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              fontSize: '16px',
              fontWeight: 'bold',
              cursor: loading ? 'not-allowed' : 'pointer',
              transition: 'background-color 0.2s'
            }}
          >
            {loading ? 'Mendaftar...' : 'Daftar'}
          </button>
        </form>

        <div style={{
          marginTop: '20px',
          textAlign: 'center',
          fontSize: '14px',
          color: '#666'
        }}>
          <p>Setelah pendaftaran, Kamu akan menerima sebuah Kode QR untuk akses ke sesi Photobooth.</p>
          
          {/* Debug info - remove in production */}
          {/*{fingerprint && (*/}
          {/*  <div style={{*/}
          {/*    marginTop: '15px',*/}
          {/*    padding: '10px',*/}
          {/*    backgroundColor: '#f8f9fa',*/}
          {/*    borderRadius: '4px',*/}
          {/*    fontSize: '12px',*/}
          {/*    color: '#666',*/}
          {/*    textAlign: 'left'*/}
          {/*  }}>*/}
          {/*    <strong>Device ID:</strong> {fingerprint.substring(0, 8)}...*/}
          {/*    <br />*/}
          {/*    <small>This helps prevent duplicate registrations from the same device.</small>*/}
          {/*  </div>*/}
          {/*)}*/}
        </div>
      </div>
    </div>
  )
}