'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { UserPlus, Clock, CheckCircle } from 'lucide-react'
import { useCurrencyStore } from '@/store/currencyStore'

export interface Referral {
  id: string
  name: string
  email: string
  joined_at: string
  status: 'pending' | 'active' | 'completed'
  orders_count: number
  earnings: number
}

interface ReferralTableProps {
  referrals: Referral[]
}

export default function ReferralTable({ referrals }: ReferralTableProps) {
  const formatAmount = useCurrencyStore((s) => s.formatAmount)
  const t = useTranslations('Account.referrals')
  const [currentPage, setCurrentPage] = useState(1)
  const itemsPerPage = 5

  const statusConfig: Record<Referral['status'], { label: string; icon: typeof Clock; color: string }> = {
    pending: { label: t('statusPending'), icon: Clock, color: 'text-yellow-600 bg-yellow-50' },
    active: { label: t('statusActive'), icon: UserPlus, color: 'text-blue-600 bg-blue-50' },
    completed: { label: t('statusCompleted'), icon: CheckCircle, color: 'text-green-600 bg-green-50' },
  }

  const totalPages = Math.ceil(referrals.length / itemsPerPage)
  const paginatedReferrals = referrals.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  )

  if (referrals.length === 0) {
    return (
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-8 text-center">
        <UserPlus size={48} className="mx-auto text-gray-custom mb-3" />
        <h3 className="font-semibold text-dark mb-1">{t('noReferrals')}</h3>
        <p className="text-sm text-gray-custom">{t('noReferralsDescription')}</p>
      </div>
    )
  }

  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead className="bg-gray-50 border-b border-gray-100">
            <tr>
              <th className="text-left p-4 text-sm font-semibold text-dark">{t('friend')}</th>
              <th className="text-left p-4 text-sm font-semibold text-dark">{t('dateJoined')}</th>
              <th className="text-left p-4 text-sm font-semibold text-dark">{t('status')}</th>
              <th className="text-left p-4 text-sm font-semibold text-dark">{t('orders')}</th>
              <th className="text-right p-4 text-sm font-semibold text-dark">{t('earnings')}</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {paginatedReferrals.map((referral) => {
              const StatusIcon = statusConfig[referral.status].icon
              return (
                <tr key={referral.id} className="hover:bg-gray-50 transition">
                  <td className="p-4">
                    <div>
                      <p className="font-medium text-dark">{referral.name}</p>
                      <p className="text-xs text-gray-custom">{referral.email}</p>
                    </div>
                  </td>
                  <td className="p-4 text-sm text-gray-custom">{new Date(referral.joined_at).toLocaleDateString()}</td>
                  <td className="p-4">
                    <span className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium ${statusConfig[referral.status].color}`}>
                      <StatusIcon size={12} />
                      {statusConfig[referral.status].label}
                    </span>
                  </td>
                  <td className="p-4 text-sm text-dark">{referral.orders_count}</td>
                  <td className="p-4 text-right">
                    <span className="font-semibold text-primary">{formatAmount(referral.earnings)}</span>
                  </td>
                </tr>
              )
            })}
          </tbody>
        </table>
      </div>

      {totalPages > 1 && (
        <div className="flex justify-center gap-2 p-4 border-t border-gray-100">
          <button
            onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
            disabled={currentPage === 1}
            className="px-3 py-1 rounded-lg border border-gray-200 text-sm disabled:opacity-50"
          >
            {t('previous')}
          </button>
          <span className="px-3 py-1 text-sm text-dark">
            {t('pageOf', { current: currentPage, total: totalPages })}
          </span>
          <button
            onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
            disabled={currentPage === totalPages}
            className="px-3 py-1 rounded-lg border border-gray-200 text-sm disabled:opacity-50"
          >
            {t('next')}
          </button>
        </div>
      )}
    </div>
  )
}
