import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Typography,
  Box,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
} from '@mui/material';
import { useState, useEffect } from 'react';
import { useSnackbar } from 'notistack';
import axios from 'axios';
import axiosInstancee from '@/utils/axios';

interface Task {
  id: number;
  name: string;
  status: string;
  deletedAt: string | null;
}

interface Reward {
  id: number;
  title: string;
  status: string;
}

interface Props {
  open: boolean;
  onClose: VoidFunction;
  type: 'assign' | 'remove';
  title: string;
}

export default function RewardActionDialog({ 
  open, 
  onClose, 
  type, 
  title 
}: Props) {
  const { enqueueSnackbar } = useSnackbar();
  const [selectedTask, setSelectedTask] = useState<number | ''>('');
  const [selectedReward, setSelectedReward] = useState<number | ''>('');
  const [tasks, setTasks] = useState<Task[]>([]);
  const [rewards, setRewards] = useState<Reward[]>([]);

  useEffect(() => {
    if (open) {
      // Fetch tasks
      axiosInstancee.get(`/api/projects/without-reward`)
        .then(response => {
          const activeTasks = response.data.filter((task: Task) => !task.deletedAt);
          setTasks(activeTasks);
        })
        .catch(error => {
          console.error('Error fetching tasks:', error);
          enqueueSnackbar('Failed to fetch tasks', { variant: 'error' });
        });

      // Fetch rewards for assign action
      if (type === 'assign') {
        axiosInstancee.get('/api/projects/rewards')
          .then(response => {
            // Get published rewards from the content array
            const publishedRewards = response.data.content.filter(
              (reward: Reward) => reward.status === 'PUBLISHED'
            );
            setRewards(publishedRewards);
          })
          .catch(error => {
            enqueueSnackbar('Failed to fetch rewards', { variant: 'error' });
          });
      }
    } else {
      // Reset selections when dialog closes
      setSelectedTask('');
      setSelectedReward('');
    }
  }, [open, type, enqueueSnackbar]);

  const handleAction = () => {
    if (type === 'assign' && (!selectedTask || !selectedReward)) {
      enqueueSnackbar('Please select both task and reward', { variant: 'error' });
      return;
    }

    if (type === 'remove' && !selectedTask) {
      enqueueSnackbar('Please select a task', { variant: 'error' });
      return;
    }

    const action = type === 'assign'
      ? axiosInstancee.post('/api/projects/assign', null, {
          params: {
            taskId: selectedTask,
            rewardId: selectedReward
          }
        })
      : axiosInstancee.delete(`/api/projects/${selectedTask}/remove-reward`);

    action
      .then(() => {
        enqueueSnackbar(
          type === 'assign' ? 'Reward assigned successfully!' : 'Reward removed successfully!', 
          { variant: 'success' }
        );
        onClose();
      })
      .catch((error) => {
        enqueueSnackbar(
          error.response?.data?.message || `Failed to ${type} reward`, 
          { variant: 'error' }
        );
      });
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>{title}</DialogTitle>
      <DialogContent>
        <Box sx={{ mt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}>
          <FormControl fullWidth>
            <InputLabel>Select Task</InputLabel>
            <Select
              value={selectedTask}
              onChange={(e) => setSelectedTask(e.target.value as number)}
              label="Select Task"
            >
              {tasks.length === 0 ? (
                <MenuItem disabled>No tasks available</MenuItem>
              ) : (
                tasks.map((task) => (
                  <MenuItem key={task.id} value={task.id}>
                    {task.name} ({task.status})
                  </MenuItem>
                ))
              )}
            </Select>
          </FormControl>

          {type === 'assign' && (
            <FormControl fullWidth>
              <InputLabel>Select Reward</InputLabel>
              <Select
                value={selectedReward}
                onChange={(e) => setSelectedReward(e.target.value as number)}
                label="Select Reward"
              >
                {rewards.length === 0 ? (
                  <MenuItem disabled>No rewards available</MenuItem>
                ) : (
                  rewards.map((reward) => (
                    <MenuItem key={reward.id} value={reward.id}>
                      {reward.title} ({reward.status})
                    </MenuItem>
                  ))
                )}
              </Select>
            </FormControl>
          )}
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} color="inherit" variant="outlined">
          Cancel
        </Button>
        <Button 
          onClick={handleAction} 
          variant="contained" 
          color={type === 'assign' ? 'primary' : 'error'}
        >
          {type === 'assign' ? 'Assign' : 'Remove'}
        </Button>
      </DialogActions>
    </Dialog>
  );
} 