'use client'

import { useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import AccountLayout from '@/components/frontend/account/AccountLayout'
import EarningsSummary from '@/components/frontend/referral/EarningsSummary'
import EarningsHistory, { type Earning } from '@/components/frontend/referral/EarningsHistory'

interface EarningsData {
  totalEarnings: number
  pendingAmount: number
  withdrawnAmount: number
  availableBalance: number
  history: Earning[]
}

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

  useEffect(() => {
    fetch('/api/frontend/earnings', { 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>
    )
  }

  return (
    <AccountLayout title={t('title')} description={t('description')}>
      <div className="space-y-6">
        <EarningsSummary
          totalEarnings={data.totalEarnings}
          withdrawnAmount={data.withdrawnAmount}
          availableBalance={data.availableBalance}
          pendingAmount={data.pendingAmount}
        />
        <EarningsHistory earnings={data.history} />
      </div>
    </AccountLayout>
  )
}
