import React, { useState, useEffect } from 'react';
import { useSoulStream } from '../contexts/SoulStreamContext';
import type { RewardsComponentProps, RewardsData } from '../types';

/**
 * RewardsComponent displays reward information from the SoulStream protocol
 */
const RewardsComponent: React.FC<RewardsComponentProps> = ({ 
  walletAddress, 
  showClaimed = true, 
  showUnclaimed = true 
}) => {
  const [rewardsData, setRewardsData] = useState<RewardsData | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  
  const { getRewards, claimReward } = useSoulStream();
  
  useEffect(() => {
    const fetchRewards = async () => {
      if (!walletAddress) return;
      
      try {
        setLoading(true);
        const data = await getRewards(walletAddress);
        setRewardsData(data);
        setError(null);
      } catch (err) {
        console.error('Failed to fetch rewards data:', err);
        setError('Failed to load rewards data');
      } finally {
        setLoading(false);
      }
    };
    
    fetchRewards();
  }, [walletAddress, getRewards]);
  
  const handleClaimReward = async (rewardId: string) => {
    try {
      await claimReward(walletAddress, rewardId);
      // Refresh rewards data after claiming
      const updatedData = await getRewards(walletAddress);
      setRewardsData(updatedData);
    } catch (err) {
      console.error('Failed to claim reward:', err);
      setError('Failed to claim reward');
    }
  };
  
  if (loading) return <div>Loading rewards data...</div>;
  if (error) return <div>Error: {error}</div>;
  if (!rewardsData) return <div>No rewards data available</div>;
  
  return (
    <div className="rewards-component">
      <h3>Rewards</h3>
      
      {showUnclaimed && rewardsData.unclaimed.length > 0 && (
        <div className="unclaimed-rewards">
          <h4>Unclaimed Rewards</h4>
          <ul>
            {rewardsData.unclaimed.map(reward => (
              <li key={reward.id}>
                <div>{reward.name} - {reward.amount}</div>
                <button onClick={() => handleClaimReward(reward.id)}>
                  Claim Reward
                </button>
              </li>
            ))}
          </ul>
        </div>
      )}
      
      {showClaimed && rewardsData.claimed.length > 0 && (
        <div className="claimed-rewards">
          <h4>Claimed Rewards</h4>
          <ul>
            {rewardsData.claimed.map(reward => (
              <li key={reward.id}>
                <div>{reward.name} - {reward.amount}</div>
                <div>Claimed on: {new Date(reward.claimedAt).toLocaleDateString()}</div>
              </li>
            ))}
          </ul>
        </div>
      )}
      
      {rewardsData.claimed.length === 0 && rewardsData.unclaimed.length === 0 && (
        <div>No rewards available</div>
      )}
    </div>
  );
};

export default RewardsComponent;