import { useEffect, useState } from 'react';
import { ITaskItem } from '@/contexts/types/tasks';
import { useBoolean } from '@/hooks';
import Iconify from '@/shared/components/iconify';
import { fDate } from '@/utils/format-time';
import {
  Button,
  Card,
  CardHeader,
  Divider,
  ListItemText,
  Stack,
  
} from '@mui/material';
import RewardAddMarkDialog from './add-mark-dialog'; // Ensure this import
import axiosInstancee from '@/utils/axios';


type Props = {
  rewardId: number; // Reward ID for fetching tasks
};

export default function TasksMarks({ rewardId }: Props) {
  const [tasks, setTasks] = useState<ITaskItem[]>([]); // Store tasks
  const [selectedTask, setSelectedTask] = useState<ITaskItem | null>(null);
  const addMarkDialog = useBoolean();
  const showMore = useBoolean(); // For "Show More / Show Less"

  const fetchTasks = async () => {
    try {
      const response = await axiosInstancee.get(`/api/projects/${rewardId}/tach`);
      if (response.data) {
        setTasks(response.data);
      }
    } catch (error) {
      console.error('Error fetching tasks:', error);
    }
  };

  useEffect(() => {
    fetchTasks();
  }, [rewardId]);

  // Handle opening the Add Mark dialog
  const handleOpenDialog = (task: ITaskItem) => {
    setSelectedTask(task);
    addMarkDialog.onTrue();
  };

  const handleMarkAdded = (updatedTask: ITaskItem) => {
    // Update the specific task in the list
    setTasks(currentTasks => 
      currentTasks.map(task => 
        task.id === updatedTask.id ? updatedTask : task
      )
    );
    addMarkDialog.onFalse();
  };

  return (
    <Stack sx={{ mx: 'auto' }}>
      <Card sx={{ maxHeight: 600 }}>
        <CardHeader title="Tasks Marks" />
        <Divider sx={{ borderStyle: 'dashed', my: 4 }} />
        <Stack spacing={1.5} sx={{ px: 3, pt: 0 }}>
          {tasks.map((task) => (
            <Stack key={task.id} direction="row" alignItems="center">
              <ListItemText
                primary={task.name}
                secondary={fDate(task.startDate)}
                primaryTypographyProps={{
                  typography: 'body2',
                }}
                secondaryTypographyProps={{
                  mt: 0.5,
                  component: 'span',
                  typography: 'caption',
                  color: 'text.disabled',
                }}
              />
              <Button
                size="small"
                color={task.point ? 'primary' : 'inherit'}
                startIcon={
                  <Iconify
                    width={16}
                    icon={
                      task.point
                        ? 'material-symbols:bookmarks'
                        : 'mingcute:add-line'
                    }
                    sx={{ mr: -0.5 }}
                  />
                }
                onClick={() => handleOpenDialog(task)}
              >
                {task.point ? `${task.point} Marks` : 'Add Mark'}
              </Button>
            </Stack>
          ))}
          <Divider sx={{ borderStyle: 'dashed' }} />
        </Stack>
        <Stack alignItems="flex-start" sx={{ p: 2 }}>
          <Button
            size="small"
            color="inherit"
            startIcon={
              <Iconify
                icon={showMore.value ? 'eva:arrow-ios-upward-fill' : 'eva:arrow-ios-downward-fill'}
              />
            }
            onClick={showMore.onToggle}
          >
            {showMore.value ? `Show Less` : `Show More`}
          </Button>
        </Stack>
      </Card>

      {/* Add Mark Dialog */}
      <RewardAddMarkDialog
        open={addMarkDialog.value}
        onClose={addMarkDialog.onFalse}
        task={selectedTask}
        onSuccess={handleMarkAdded}
      />
    </Stack>
  );
}