'use client'

import { useEffect, useState } from 'react'
import { useAffiliateStore } from '@/store/affiliate-store'
import { Users, DollarSign, Wallet, TrendingUp, Copy, Check, AlertTriangle } from 'lucide-react'
import toast from 'react-hot-toast'
import { formatCurrency } from '@/lib/utils'

export default function AffiliateDashboardPage() {
  const { affiliate } = useAffiliateStore()
  const [data, setData] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [copied, setCopied] = useState(false)

  useEffect(() => {
    fetch('/api/affiliate/dashboard')
      .then(res => res.json())
      .then(setData)
      .catch(console.error)
      .finally(() => setLoading(false))
  }, [])

  const copyReferralLink = () => {
    const link = `${window.location.origin}/register?ref=${data?.referralCode || affiliate?.referralCode}`
    navigator.clipboard.writeText(link)
    setCopied(true)
    toast.success('Link referral disalin!')
    setTimeout(() => setCopied(false), 2000)
  }

  const copyCode = () => {
    navigator.clipboard.writeText(data?.referralCode || affiliate?.referralCode || '')
    toast.success('Kode referral disalin!')
  }

  if (loading) {
    return <div className="flex justify-center py-12"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-emerald-600"></div></div>
  }

  if (!affiliate?.isActive) {
    return (
      <div>
        <div className="bg-yellow-50 border border-yellow-200 rounded-xl p-6 flex items-start gap-4">
          <AlertTriangle className="w-6 h-6 text-yellow-600 flex-shrink-0 mt-0.5" />
          <div>
            <h3 className="text-lg font-semibold text-yellow-800">Menunggu Persetujuan</h3>
            <p className="text-yellow-700 mt-1">Akun affiliate Anda sedang menunggu persetujuan dari admin. Anda akan mendapatkan akses penuh setelah akun disetujui.</p>
          </div>
        </div>

        <div className="mt-6 card">
          <h3 className="font-semibold text-gray-900 mb-2">Kode Referral Anda</h3>
          <div className="flex items-center gap-3">
            <code className="text-2xl font-bold text-emerald-600 bg-emerald-50 px-4 py-2 rounded-lg">{data?.referralCode || affiliate?.referralCode}</code>
            <button onClick={copyCode} className="text-gray-400 hover:text-gray-600"><Copy className="w-5 h-5" /></button>
          </div>
          <p className="text-sm text-gray-500 mt-2">Kode ini akan aktif setelah akun Anda disetujui</p>
        </div>
      </div>
    )
  }

  const stats = data?.stats || {}

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold text-gray-900">Dashboard</h1>

      {/* Referral Code Section */}
      <div className="card bg-emerald-50 border-emerald-200">
        <div className="flex flex-col sm:flex-row sm:items-center gap-4">
          <div className="flex-1">
            <p className="text-sm text-emerald-700 font-medium">Kode Referral Anda</p>
            <div className="flex items-center gap-3 mt-1">
              <code className="text-2xl font-bold text-emerald-700">{data?.referralCode}</code>
              <button onClick={copyCode} className="text-emerald-600 hover:text-emerald-800"><Copy className="w-5 h-5" /></button>
            </div>
          </div>
          <button onClick={copyReferralLink}
            className="flex items-center gap-2 px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 text-sm font-medium">
            {copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
            {copied ? 'Disalin!' : 'Salin Link Referral'}
          </button>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="card">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-blue-100 rounded-lg"><Users className="w-5 h-5 text-blue-600" /></div>
            <div>
              <p className="text-sm text-gray-500">Total Referral</p>
              <p className="text-xl font-bold text-gray-900">{stats.totalReferrals || 0}</p>
            </div>
          </div>
        </div>
        <div className="card">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-green-100 rounded-lg"><TrendingUp className="w-5 h-5 text-green-600" /></div>
            <div>
              <p className="text-sm text-gray-500">Referral Aktif</p>
              <p className="text-xl font-bold text-gray-900">{stats.activeReferrals || 0}</p>
            </div>
          </div>
        </div>
        <div className="card">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-purple-100 rounded-lg"><DollarSign className="w-5 h-5 text-purple-600" /></div>
            <div>
              <p className="text-sm text-gray-500">Total Komisi</p>
              <p className="text-xl font-bold text-gray-900">{formatCurrency(stats.totalCommission || 0)}</p>
            </div>
          </div>
        </div>
        <div className="card">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-emerald-100 rounded-lg"><Wallet className="w-5 h-5 text-emerald-600" /></div>
            <div>
              <p className="text-sm text-gray-500">Saldo</p>
              <p className="text-xl font-bold text-gray-900">{formatCurrency(stats.walletBalance || 0)}</p>
            </div>
          </div>
        </div>
      </div>

      {/* Recent Commissions */}
      <div className="card">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">Komisi Terbaru</h2>
        {data?.recentCommissions?.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-gray-200">
                  <th className="text-left py-2 font-medium text-gray-500">Tenant</th>
                  <th className="text-right py-2 font-medium text-gray-500">Komisi</th>
                  <th className="text-right py-2 font-medium text-gray-500">Rate</th>
                  <th className="text-right py-2 font-medium text-gray-500">Tanggal</th>
                </tr>
              </thead>
              <tbody>
                {data.recentCommissions.map((c: any) => (
                  <tr key={c.id} className="border-b border-gray-100">
                    <td className="py-2 text-gray-900">{c.tenantName}</td>
                    <td className="py-2 text-right text-emerald-600 font-medium">{formatCurrency(c.commissionAmount)}</td>
                    <td className="py-2 text-right text-gray-500">{c.commissionRate}%</td>
                    <td className="py-2 text-right text-gray-500">{new Date(c.createdAt).toLocaleDateString('id-ID')}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <p className="text-gray-500 text-center py-8">Belum ada komisi</p>
        )}
      </div>
    </div>
  )
}
