import React, { useState, useEffect } from 'react';
import { useService } from '../../../core/di/ServiceContainer';
import { IRewardService } from '../services/interfaces/IRewardService';
import { Reward, RewardType, RewardStatus } from '../types/reward.types';

interface RewardDashboardProps {
  userId?: string;
  className?: string;
}

interface RewardStats {
  totalEarned: number;
  pendingRewards: number;
  thisMonthEarnings: number;
  rewardsByType: Record<RewardType, number>;
}

export const RewardDashboard: React.FC<RewardDashboardProps> = ({ 
  userId = 'current-user', 
  className = '' 
}) => {
  const rewardService = useService<IRewardService>('reward-service');
  const [rewards, setRewards] = useState<Reward[]>([]);
  const [stats, setStats] = useState<RewardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedPeriod, setSelectedPeriod] = useState<'week' | 'month' | 'quarter'>('month');

  useEffect(() => {
    if (rewardService) {
      loadRewardData();
    } else {
      // Reset loading state if service is not available
      setLoading(false);
    }
  }, [userId, selectedPeriod, rewardService]);

  const loadRewardData = async () => {
    if (!rewardService) {
      setError('Reward service not available');
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      setError(null);

      // Calculate date range based on selected period
      const endDate = new Date();
      const startDate = new Date();
      
      switch (selectedPeriod) {
        case 'week':
          startDate.setDate(endDate.getDate() - 7);
          break;
        case 'month':
          startDate.setMonth(endDate.getMonth() - 1);
          break;
        case 'quarter':
          startDate.setMonth(endDate.getMonth() - 3);
          break;
      }

      // Load rewards for the period
      const userRewards = await rewardService.getRewardsByUserId(userId, {
        dateFrom: startDate,
        dateTo: endDate
      });

      // Load user statistics
      const userStats = await rewardService.getUserRewardStatistics(userId);

      setRewards(userRewards);
      setStats({
        totalEarned: userStats.totalEarned,
        pendingRewards: userStats.totalPending,
        thisMonthEarnings: userRewards
          .filter(r => r.status === RewardStatus.APPROVED)
          .reduce((sum, r) => sum + r.amount, 0),
        rewardsByType: userStats.rewardBreakdown.reduce((acc, item) => {
          acc[item.type] = item.totalAmount;
          return acc;
        }, {} as Record<RewardType, number>)
      });
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load reward data');
    } finally {
      setLoading(false);
    }
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('id-ID', {
      style: 'currency',
      currency: 'IDR'
    }).format(amount);
  };

  const getRewardTypeLabel = (type: RewardType) => {
    const labels = {
      [RewardType.LEARNING_HOURS]: 'Jam Belajar',
      [RewardType.PERFORMANCE_BONUS]: 'Bonus Performa',
      [RewardType.COMPLETION_REWARD]: 'Reward Penyelesaian',
      [RewardType.CONSISTENCY_REWARD]: 'Bonus Konsistensi'
    };
    return labels[type] || type;
  };

  const getStatusBadge = (status: RewardStatus) => {
    const statusConfig = {
      [RewardStatus.PENDING]: { label: 'Menunggu', className: 'bg-yellow-100 text-yellow-800' },
      [RewardStatus.APPROVED]: { label: 'Disetujui', className: 'bg-green-100 text-green-800' },
      [RewardStatus.REJECTED]: { label: 'Ditolak', className: 'bg-red-100 text-red-800' },
      [RewardStatus.PAID]: { label: 'Dibayar', className: 'bg-blue-100 text-blue-800' }
    };

    const config = statusConfig[status];
    return (
      <span className={`px-2 py-1 rounded-full text-xs font-medium ${config.className}`}>
        {config.label}
      </span>
    );
  };

  if (loading) {
    return (
      <div className={`bg-white rounded-lg shadow-md p-6 ${className}`}>
        <div className="animate-pulse">
          <div className="h-6 bg-gray-200 rounded mb-4"></div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            {[1, 2, 3].map(i => (
              <div key={i} className="h-20 bg-gray-200 rounded"></div>
            ))}
          </div>
          <div className="h-64 bg-gray-200 rounded"></div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className={`bg-white rounded-lg shadow-md p-6 ${className}`}>
        <div className="text-center text-error-600">
          <p className="text-lg font-semibold mb-2">Error</p>
          <p>{error}</p>
          <button 
            onClick={loadRewardData}
            className="mt-4 px-4 py-2 bg-primary-600 text-white rounded hover:bg-primary-700"
          >
            Coba Lagi
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className={`bg-white rounded-lg shadow-md p-6 ${className}`}>
      {/* Header */}
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold text-gray-900">Dashboard Reward</h2>
        <div className="flex space-x-2">
          {(['week', 'month', 'quarter'] as const).map(period => (
            <button
              key={period}
              onClick={() => setSelectedPeriod(period)}
              className={`px-3 py-1 rounded text-sm font-medium ${
                selectedPeriod === period
                  ? 'bg-primary-600 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              {period === 'week' ? 'Minggu' : period === 'month' ? 'Bulan' : 'Kuartal'}
            </button>
          ))}
        </div>
      </div>

      {/* Statistics Cards */}
      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
          <div className="rounded-lg p-4" style={{ backgroundColor: '#071e49', color: '#ffffff' }}>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-primary-100 text-sm">Total Earned</p>
                <p className="text-2xl font-bold">{formatCurrency(stats.totalEarned)}</p>
              </div>
              <div className="text-3xl opacity-80">💰</div>
            </div>
          </div>

          <div className="rounded-lg p-4" style={{ backgroundColor: '#071e49', color: '#ffffff' }}>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-success-100 text-sm">Periode Ini</p>
                <p className="text-2xl font-bold">{formatCurrency(stats.thisMonthEarnings)}</p>
              </div>
              <div className="text-3xl opacity-80">📈</div>
            </div>
          </div>

          <div className="rounded-lg p-4" style={{ backgroundColor: '#071e49', color: '#ffffff' }}>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-warning-100 text-sm">Pending</p>
                <p className="text-2xl font-bold">{formatCurrency(stats.pendingRewards)}</p>
              </div>
              <div className="text-3xl opacity-80">⏳</div>
            </div>
          </div>
        </div>
      )}

      {/* Reward Type Breakdown */}
      {stats && (
        <div className="mb-6">
          <h3 className="text-lg font-semibold mb-3">Breakdown by Type</h3>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            {Object.entries(stats.rewardsByType).map(([type, amount]) => (
              <div key={type} className="bg-gray-50 rounded-lg p-3 text-center">
                <p className="text-sm text-gray-600 mb-1">
                  {getRewardTypeLabel(type as RewardType)}
                </p>
                <p className="font-semibold text-gray-900">
                  {formatCurrency(amount)}
                </p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Recent Rewards */}
      <div>
        <h3 className="text-lg font-semibold mb-3">Recent Rewards</h3>
        {rewards.length === 0 ? (
          <div className="text-center py-8 text-gray-500">
            <div className="text-4xl mb-2">🎯</div>
            <p>Belum ada reward untuk periode ini</p>
            <p className="text-sm">Mulai belajar untuk mendapatkan reward!</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Tanggal
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Tipe
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Deskripsi
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Jumlah
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Status
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {rewards.slice(0, 10).map((reward) => (
                  <tr key={reward.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                      {reward.createdAt.toLocaleDateString('id-ID')}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                      {getRewardTypeLabel(reward.type)}
                    </td>
                    <td className="px-6 py-4 text-sm text-gray-900">
                      {reward.description}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                      {formatCurrency(reward.amount)}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      {getStatusBadge(reward.status)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* View All Link */}
      {rewards.length > 10 && (
        <div className="mt-4 text-center">
          <button className="text-primary-600 hover:text-primary-800 font-medium">
            Lihat Semua Reward ({rewards.length})
          </button>
        </div>
      )}
    </div>
  );
};