'use client'

import { useState, useEffect } from 'react'
import { useSearchParams } from 'next/navigation'

interface User {
  id: number
  username: string
  email: string
}

interface AuthModalProps {
  isOpen: boolean
  onClose: () => void
  onLogin: (user: User) => void
}

export default function AuthModal({ isOpen, onClose, onLogin }: AuthModalProps) {
  const searchParams = useSearchParams()
  const [isLogin, setIsLogin] = useState(true)
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [email, setEmail] = useState('')
  const [referralId, setReferralId] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (isOpen) {
      // Reset form when modal opens
      setUsername('')
      setPassword('')
      setEmail('')
      setError('')
      setIsLogin(true)
      
      // Auto-fill referral ID from URL if present
      const refFromUrl = searchParams?.get('ref')
      if (refFromUrl) {
        setReferralId(refFromUrl)
      } else {
        setReferralId('')
      }
    }
  }, [isOpen, searchParams])

  // Update referral ID when switching to register mode and URL has ref parameter
  useEffect(() => {
    if (!isLogin) {
      const refFromUrl = searchParams?.get('ref')
      if (refFromUrl && !referralId) {
        setReferralId(refFromUrl)
      }
    }
  }, [isLogin, searchParams, referralId])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')
    setLoading(true)

    try {
      const endpoint = isLogin ? '/api/auth/login' : '/api/auth/register'
      
      // Use referral ID from input field, or fall back to URL parameter
      const referralIdToUse = !isLogin && referralId.trim() 
        ? referralId.trim() 
        : (!isLogin ? searchParams?.get('ref') : null)
      
      const body = isLogin
        ? { username, password }
        : { username, password, email, referral_id: referralIdToUse }

      const response = await fetch(endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(body),
        credentials: 'include', // Important for cookies
      })

      const data = await response.json()

      if (!response.ok) {
        setError(data.error || 'An error occurred')
        setLoading(false)
        return
      }

      // Success - call onLogin callback and close modal
      onLogin(data.user)
      onClose()
    } catch (error) {
      console.error('Auth error:', error)
      setError('An unexpected error occurred')
    } finally {
      setLoading(false)
    }
  }

  if (!isOpen) return null

  return (
    <div
      style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: 'rgba(0, 0, 0, 0.7)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: 1000,
        padding: '20px',
      }}
      onClick={onClose}
    >
      <div
        style={{
          background: 'var(--card)',
          borderRadius: '16px',
          padding: '32px',
          maxWidth: '400px',
          width: '100%',
          boxShadow: '0 20px 60px rgba(0, 0, 0, 0.3)',
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
          <h2 style={{ margin: 0 }}>
            {isLogin ? 'Login' : 'Register'}
          </h2>
          <button
            onClick={onClose}
            style={{
              background: 'transparent',
              border: 'none',
              fontSize: '24px',
              cursor: 'pointer',
              color: 'var(--muted)',
              padding: 0,
              width: '32px',
              height: '32px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            ×
          </button>
        </div>

        <form onSubmit={handleSubmit}>
          {!isLogin && (
            <div style={{ marginBottom: '16px' }}>
              <label
                htmlFor="email"
                style={{
                  display: 'block',
                  marginBottom: '8px',
                  fontSize: '14px',
                  color: 'var(--text)',
                }}
              >
                Email
              </label>
              <input
                type="email"
                id="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
                style={{
                  width: '100%',
                  padding: '12px',
                  borderRadius: '8px',
                  border: '1px solid var(--border)',
                  background: 'var(--bg-soft)',
                  color: 'var(--text)',
                  fontSize: '14px',
                }}
                placeholder="your@email.com"
              />
            </div>
          )}

          <div style={{ marginBottom: '16px' }}>
            <label
              htmlFor="username"
              style={{
                display: 'block',
                marginBottom: '8px',
                fontSize: '14px',
                color: 'var(--text)',
              }}
            >
              Username
            </label>
            <input
              type="text"
              id="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
              minLength={isLogin ? undefined : 3}
              style={{
                width: '100%',
                padding: '12px',
                borderRadius: '8px',
                border: '1px solid var(--border)',
                background: 'var(--bg-soft)',
                color: 'var(--text)',
                fontSize: '14px',
              }}
              placeholder="username"
            />
          </div>

          <div style={{ marginBottom: '16px' }}>
            <label
              htmlFor="password"
              style={{
                display: 'block',
                marginBottom: '8px',
                fontSize: '14px',
                color: 'var(--text)',
              }}
            >
              Password
            </label>
            <input
              type="password"
              id="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              minLength={isLogin ? undefined : 6}
              style={{
                width: '100%',
                padding: '12px',
                borderRadius: '8px',
                border: '1px solid var(--border)',
                background: 'var(--bg-soft)',
                color: 'var(--text)',
                fontSize: '14px',
              }}
              placeholder="password"
            />
          </div>

          {!isLogin && (
            <div style={{ marginBottom: '20px' }}>
              <label
                htmlFor="referralId"
                style={{
                  display: 'block',
                  marginBottom: '8px',
                  fontSize: '14px',
                  color: 'var(--text)',
                }}
              >
                Referral ID <span style={{ color: 'var(--muted)', fontSize: '12px', fontWeight: 'normal' }}>(optional)</span>
              </label>
              <input
                type="text"
                id="referralId"
                value={referralId}
                onChange={(e) => setReferralId(e.target.value)}
                style={{
                  width: '100%',
                  padding: '12px',
                  borderRadius: '8px',
                  border: '1px solid var(--border)',
                  background: 'var(--bg-soft)',
                  color: 'var(--text)',
                  fontSize: '14px',
                }}
                placeholder="Enter referral ID"
              />
              {searchParams?.get('ref') && referralId === searchParams.get('ref') && (
                <small style={{ display: 'block', marginTop: '4px', fontSize: '12px', color: 'var(--accent)' }}>
                  ✓ Auto-filled from referral link
                </small>
              )}
            </div>
          )}

          {error && (
            <div
              style={{
                padding: '12px',
                background: 'rgba(255, 0, 0, 0.1)',
                border: '1px solid rgba(255, 0, 0, 0.3)',
                borderRadius: '8px',
                color: '#ff4444',
                fontSize: '14px',
                marginBottom: '16px',
              }}
            >
              {error}
            </div>
          )}

          <button
            type="submit"
            disabled={loading}
            className="cta"
            style={{
              width: '100%',
              padding: '12px',
              cursor: loading ? 'not-allowed' : 'pointer',
              opacity: loading ? 0.6 : 1,
            }}
          >
            {loading
              ? 'Processing...'
              : isLogin
                ? 'Login'
                : 'Register'}
          </button>
        </form>

        <div
          style={{
            marginTop: '20px',
            textAlign: 'center',
            fontSize: '14px',
            color: 'var(--muted)',
          }}
        >
          {isLogin ? (
            <>
              Don't have an account?{' '}
              <button
                onClick={() => {
                  setIsLogin(false)
                  setError('')
                }}
                style={{
                  background: 'transparent',
                  border: 'none',
                  color: 'var(--accent)',
                  cursor: 'pointer',
                  textDecoration: 'underline',
                  padding: 0,
                }}
              >
                Register
              </button>
            </>
          ) : (
            <>
              Already have an account?{' '}
              <button
                onClick={() => {
                  setIsLogin(true)
                  setError('')
                }}
                style={{
                  background: 'transparent',
                  border: 'none',
                  color: 'var(--accent)',
                  cursor: 'pointer',
                  textDecoration: 'underline',
                  padding: 0,
                }}
              >
                Login
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  )
}

