'use client'

import { useState, useEffect } from 'react'
import UnlockModal from './UnlockModal'
import { useI18n } from '@/lib/i18n'

interface ReferralTier {
  referralsNeeded: number
  referralsRemaining: number
  isUnlocked: boolean
}

interface ReferralStatus {
  referralCount: number
  isUnlocked: boolean
  referralsNeeded: number
  referralsRemaining: number
  wholesaleTier?: ReferralTier
  innerCircleTier?: ReferralTier
}

export default function UnlockBar() {
  const { t } = useI18n()
  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,
        wholesaleTier: {
          referralsNeeded: 3,
          referralsRemaining: 3,
          isUnlocked: false
        },
        innerCircleTier: {
          referralsNeeded: 10,
          referralsRemaining: 10,
          isUnlocked: false
        }
      })
    } 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,
    wholesaleTier: {
      referralsNeeded: 3,
      referralsRemaining: 3,
      isUnlocked: false
    },
    innerCircleTier: {
      referralsNeeded: 10,
      referralsRemaining: 10,
      isUnlocked: false
    }
  }

  const wholesaleTier = status.wholesaleTier || {
    referralsNeeded: 3,
    referralsRemaining: Math.max(0, 3 - status.referralCount),
    isUnlocked: status.isUnlocked
  }

  const innerCircleTier = status.innerCircleTier || {
    referralsNeeded: 10,
    referralsRemaining: Math.max(0, 10 - status.referralCount),
    isUnlocked: status.referralCount >= 10
  }

  // If wholesale is unlocked but inner circle is not, show inner circle as next level
  if (wholesaleTier.isUnlocked && !innerCircleTier.isUnlocked) {
    return (
      <>
        <div className="unlock-bar" style={{ background: 'var(--accent)', color: '#000' }}>
          <div>
            {t('unlockBar.unlocked')} <strong>{t('unlockBar.unlockedText')}</strong>
          </div>
        </div>
        <div className="unlock-bar">
          <div>
            {t('unlockBar.innerCircleLocked')} <strong>{t('unlockBar.referralsCompleted', { count: status.referralCount, needed: innerCircleTier.referralsNeeded })}</strong> · {t('unlockBar.toGo', { remaining: innerCircleTier.referralsRemaining })}
            <br />
            <small>{t('unlockBar.innerCircleUnlockText', { needed: innerCircleTier.referralsNeeded })}</small>
            <a href="#unlock" onClick={handleUnlockClick}>{t('unlockBar.unlockNow')}</a>
          </div>
        </div>
        <UnlockModal isOpen={showModal} onClose={() => setShowModal(false)} />
      </>
    )
  }

  // If both are unlocked, show success message
  if (wholesaleTier.isUnlocked && innerCircleTier.isUnlocked) {
    return (
      <div className="unlock-bar" style={{ background: 'var(--accent)', color: '#000' }}>
        <div>
          {t('unlockBar.unlocked')} <strong>{t('unlockBar.unlockedText')}</strong> · {t('unlockBar.innerCircleUnlocked')}
        </div>
      </div>
    )
  }

  // Show wholesale unlock progress
  return (
    <>
      <div className="unlock-bar">
        <div>
          {t('unlockBar.locked')} <strong>{t('unlockBar.referralsCompleted', { count: status.referralCount, needed: wholesaleTier.referralsNeeded })}</strong> · {t('unlockBar.toGo', { remaining: wholesaleTier.referralsRemaining })}
          <br />
          <small>{t('unlockBar.unlockText', { needed: wholesaleTier.referralsNeeded })}</small>
          <a href="#unlock" onClick={handleUnlockClick}>{t('unlockBar.unlockNow')}</a>
        </div>
      </div>
      <UnlockModal isOpen={showModal} onClose={() => setShowModal(false)} />
    </>
  )
}

