'use client'

import { useState, useEffect } from 'react'
import UnlockModal from './UnlockModal'

interface ReferralStatus {
  referralCount: number
  isUnlocked: boolean
  referralsNeeded: number
  referralsRemaining: number
}

export default function UnlockBar() {
  const [referralStatus, setReferralStatus] = useState<ReferralStatus | null>(null)
  const [showModal, setShowModal] = useState(false)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetchReferralStatus()
  }, [])

  const fetchReferralStatus = async () => {
    try {
      const response = await fetch('/api/referrals/status', {
        credentials: 'include',
      })
      const data = await response.json()
      setReferralStatus(data)
    } catch (error) {
      console.error('Error fetching referral status:', error)
      // Set default values on error
      setReferralStatus({
        referralCount: 0,
        isUnlocked: false,
        referralsNeeded: 3,
        referralsRemaining: 3,
      })
    } finally {
      setLoading(false)
    }
  }

  const handleUnlockClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
    e.preventDefault()
    setShowModal(true)
  }

  if (loading) {
    return null
  }

  const status = referralStatus || {
    referralCount: 0,
    isUnlocked: false,
    referralsNeeded: 3,
    referralsRemaining: 3,
  }

  // If unlocked, show different message or hide bar
  if (status.isUnlocked) {
    return (
      <div className="unlock-bar" style={{ background: 'var(--accent)', color: '#000' }}>
        <div>
          ✅ Wholesale prices unlocked — <strong>You have access to wholesale pricing!</strong>
        </div>
      </div>
    )
  }

  return (
    <>
      <div className="unlock-bar">
        <div>
          🔒 Wholesale prices locked — <strong>{status.referralCount} / {status.referralsNeeded} referrals completed</strong> · {status.referralsRemaining} to go
          <br />
          <small>{status.referralsNeeded} verified sign-ups unlock wholesale prices forever.</small>
          <a href="#unlock" onClick={handleUnlockClick}>Unlock now</a>
        </div>
      </div>
      <UnlockModal isOpen={showModal} onClose={() => setShowModal(false)} />
    </>
  )
}

