'use client'

import { useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import AccountLayout from '@/components/frontend/account/AccountLayout'
import ReferralCodeBox from '@/components/frontend/referral/ReferralCodeBox'
import ReferralStats from '@/components/frontend/referral/ReferralStats'
import ReferralTable, { type Referral } from '@/components/frontend/referral/ReferralTable'

interface ReferralsData {
  code: string
  referralUrl: string
  referrals: Referral[]
}

export default function ReferralsPageClient() {
  const t = useTranslations('Account.referrals')
  const [data, setData] = useState<ReferralsData | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetch('/api/frontend/referrals', { credentials: 'include' })
      .then((res) => res.json())
      .then((res) => {
        if (res.success) setData(res.data)
      })
      .finally(() => setLoading(false))
  }, [])

  if (loading || !data) {
    return (
      <AccountLayout title={t('title')} description={t('description')}>
        <div className="text-center py-12">
          <div className="animate-spin w-8 h-8 border-4 border-primary border-t-transparent rounded-full mx-auto" />
        </div>
      </AccountLayout>
    )
  }

  const totalReferrals = data.referrals.length
  const activeReferrals = data.referrals.filter((r) => r.status === 'active' || r.status === 'completed').length
  const totalEarnings = data.referrals.reduce((sum, r) => sum + r.earnings, 0)

  return (
    <AccountLayout title={t('title')} description={t('description')}>
      <div className="space-y-6">
        <ReferralCodeBox code={data.code} referralUrl={data.referralUrl} />
        <ReferralStats
          totalReferrals={totalReferrals}
          activeReferrals={activeReferrals}
          totalEarnings={totalEarnings}
        />
        <ReferralTable referrals={data.referrals} />
      </div>
    </AccountLayout>
  )
}
