import { useState } from 'react';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Pagination from '@mui/material/Pagination';
import { useSnackbar } from 'notistack';
import axios from 'axios';
import RewardItem from './reward-item';
import { IRewardItem } from '@/contexts/types/reward';
import { useRouter } from 'next/navigation';
import { paths } from '@/routes/paths';
import LoadingButton from '@mui/lab/LoadingButton';
import Iconify from '@/shared/components/iconify';
import axiosInstancee from '@/utils/axios';
import IconButton from '@mui/material/IconButton';

interface RewardListProps {
  rewards: IRewardItem[];
  onDelete: (id: string) => void;
  canManageRewards?: boolean;
}

export default function RewardList({ rewards, onDelete, canManageRewards = false }: RewardListProps) {
  const router = useRouter();
  const { enqueueSnackbar } = useSnackbar();
  const [generatingWinners, setGeneratingWinners] = useState<string | null>(null);

  const handleGenerateWinners = async (rewardId: string) => {
    setGeneratingWinners(rewardId);
    try {
      const response = await axiosInstancee.post(
        `/api/projects/${rewardId}/generate-winners`
      );
      
      enqueueSnackbar(response.data, {
        variant: 'success',
      });
    } catch (error: any) {
      enqueueSnackbar(
        error.response?.data || 'Failed to generate winners',
        { variant: 'error' }
      );
    } finally {
      setGeneratingWinners(null);
    }
  };

  const handleView = (id: string) => {
    router.push(paths.dashboard.rewards.reward_details(id));
  };

  const handleEdit = (id: string) => {
    router.push(paths.dashboard.rewards.edit(id));
  };

  const handleDelete = (id: string) => {
    if (!canManageRewards) {
      enqueueSnackbar('You do not have permission to delete rewards', { variant: 'error' });
      return;
    }
    
    onDelete(id);
  };

  return (
    <Card sx={{ p: 3 }}>
      <Box
        display="grid"
        gap={3}
        gridTemplateColumns={{
          xs: 'repeat(1, 1fr)',
          sm: 'repeat(2, 1fr)',
          md: 'repeat(3, 1fr)',
        }}
      >
        {rewards.map((reward) => (
          <Box
            key={reward.id}
            sx={{
              position: 'relative',
              '&:hover': {
                '& .actions': {
                  opacity: 1,
                },
              },
            }}
          >
            <RewardItem
              reward={reward}
              onView={() => handleView(reward.id)}
              onEdit={() => handleEdit(reward.id)}
              onDelete={() => handleDelete(reward.id)}
            />
            
            {canManageRewards && (
              <LoadingButton
                className="actions"
                loading={generatingWinners === reward.id}
                onClick={() => handleGenerateWinners(reward.id)}
                variant="contained"
                color="primary"
                startIcon={<Iconify icon="mdi:trophy-award" />}
                sx={{
                  position: 'absolute',
                  bottom: 16,
                  right: 16,
                  opacity: 0,
                  transition: 'opacity 0.2s ease-in-out',
                  bgcolor: 'background.paper',
                  '&:hover': {
                    bgcolor: 'background.neutral',
                  },
                }}
              >
                Generate Winners
              </LoadingButton>
            )}
          </Box>
        ))}
      </Box>
    </Card>
  );
}