import { Draggable } from '@hello-pangea/dnd';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack';
import Avatar from '@mui/material/Avatar';
import AvatarGroup from '@mui/material/AvatarGroup';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import { useBoolean } from '@/hooks';
import Iconify from '@/shared/components/iconify';
import { ITaskItem } from '@/contexts/types/tasks';
import { formatDate } from '@/utils/format-time';
import KanbanDetails from './kanban-details';
import { useEffect, useState } from 'react';
import { axiosInstance } from '@/utils/axios';
import Tooltip from '@mui/material/Tooltip';
import CircleIcon from '@mui/icons-material/Circle';
import Popover from '@mui/material/Popover';
import { alpha } from '@mui/material/styles';
import { Project } from '@/contexts/types/Project';

type Props = {
  task: ITaskItem;
  index: number;
  onUpdateTask: (task: ITaskItem) => void;
  onDeleteTask: (taskId: number) => void;
  displaySettings: {
    showPriority: boolean;
    showDueDate: boolean;
    showType: boolean;
    showPoints: boolean;
  };
  project: Project;
};

interface Collaborator {
  id: string;
  firstName: string;
  lastName: string;
  initials: string;
}

const COLORS = [
  '', // Add empty string for default/reset option
  '#00A76F', // green
  '#FF5630', // red
  '#FFAB00', // yellow
  '#1890FF', // blue
  '#8E33FF', // purple
  '#00B8D9', // cyan
  '#36B37E', // teal
  '#FF5C93', // pink
  '#54D62C', // bright green
  '#FFA723', // orange
];

export default function KanbanTaskItem({ task, index, onUpdateTask, onDeleteTask, displaySettings, project }: Props) {
  const [anchorElColor, setAnchorElColor] = useState<null | HTMLElement>(null);
  const [localColor, setLocalColor] = useState(task.color || '');
  const openDetails = useBoolean();
  const [collaborators, setCollaborators] = useState<Collaborator[]>([]);    

  useEffect(() => {
    const fetchCollaborators = async () => {
      console.log('Task collaboratorIds:', task.collaboratorIds);

      if (!task.collaboratorIds?.length) {
        console.log('No collaborator IDs found');
        return;
      }

      try {
        const collaboratorsData = await Promise.all(
          task.collaboratorIds.map(async (collaboratorId) => {
            const response = await axiosInstance.get(
              `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/id`,
              {
                params: { Id: collaboratorId },
              }
            );

            return {
              id: String(collaboratorId),
              firstName: response.data.user.firstName,
              lastName: response.data.user.lastName,
              initials: `${response.data.user.firstName.charAt(0)}${response.data.user.lastName.charAt(0)}`.toUpperCase()
            };
          })
        );
        setCollaborators(collaboratorsData);
      } catch (error) {
        console.error('Failed to fetch collaborators:', error);
      }
    };

    fetchCollaborators();
  }, [task.collaboratorIds]);

  const taskId = String(task.id);

  const handleOpenColorPicker = (event: React.MouseEvent<HTMLElement>) => {  
    event.stopPropagation();
    setAnchorElColor(event.currentTarget);
  };

  const handleCloseColorPicker = () => {
    setAnchorElColor(null);
  };

  const handleClickColor = (color: string) => {
    setLocalColor(color);
    handleCloseColorPicker();
  };

  return (
    <Draggable draggableId={taskId} index={index}>
      {(provided) => (
        <Paper
          ref={provided.innerRef}
          {...provided.draggableProps}
          {...provided.dragHandleProps}
          sx={{
            width: 1,
            borderRadius: 1,
            overflow: 'hidden',
            position: 'relative',
            bgcolor: localColor || 'background.paper',
            backgroundImage: localColor
              ? `linear-gradient(to bottom, ${alpha('#fff', 0.5)}, ${alpha('#fff', 0.4)})`
              : 'none',
            border: (theme) => `solid 1px ${theme.palette.divider}`,
            '&:hover': {
              boxShadow: (theme) => theme.customShadows.z20,
            },
          }}
        >
          <Stack spacing={2} sx={{ p: 2 }}>
            <Stack direction="row" alignItems="center" spacing={1}>
              <IconButton
                size="small"
                onClick={handleOpenColorPicker}
                sx={{ 
                  width: 24,
                  height: 24,
                  mr: 1,
                  bgcolor: 'background.paper',
                  border: '1px solid',
                  borderColor: 'divider',
                  '&:hover': { bgcolor: 'background.paper' },
                }}
              >
                <CircleIcon sx={{
                  color: task.color || 'action.disabled',
                  width: 16,
                  height: 16,
                }} />
              </IconButton>

              <Typography variant="subtitle2" sx={{ flexGrow: 1 }}>
                {task.name}
              </Typography>

              {task.itemStates === "FAVORITE" && (
                <Iconify icon="solar:star-bold" sx={{ color: 'warning.main' }} />
              )}
            </Stack>

            <Stack direction="row" spacing={2}>
              {displaySettings.showType && (
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>   
                  <Iconify
                    icon={
                      task.type === 'BUG' ? 'solar:bug-bold' : 'solar:widget-bold'
                    }
                    sx={{
                      color:
                        task.type === 'BUG' ? 'error.main' : 'info.main'       
                    }}
                  />
                  <Typography variant="caption">{task.type}</Typography>       
                </Box>
              )}
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>   
                <Iconify
                  icon={
                    task.status === 'TO DO' ? 'solar:clipboard-list-bold' :  
                    task.status === 'IN PROGRESS' ? 'solar:clock-circle-bold' :
                    'solar:check-circle-bold'
                  }
                  sx={{
                    color:
                      task.status === 'TO DO' ? 'info.main' :
                      task.status === 'IN PROGRESS' ? 'warning.main' :       
                      'success.main',
                  }}
                />
                <Typography variant="caption">{task.status}</Typography>     
              </Box>
            </Stack>

            <Stack direction="row" spacing={2}>
              {displaySettings.showPriority && (
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>   
                  <Iconify
                    icon={
                      task.priority === 'HIGH' ? 'solar:double-alt-arrow-up-bold' :
                      task.priority === 'MEDIUM' ? 'solar:double-alt-arrow-right-bold' :
                      'solar:double-alt-arrow-down-bold'
                    }
                    sx={{
                      color:
                        task.priority === 'HIGH' ? 'error.main' :
                        task.priority === 'MEDIUM' ? 'warning.main' :
                        'success.main',
                    }}
                  />
                  <Typography variant="caption">{task.priority}</Typography>   
                </Box>
              )}
              {displaySettings.showPoints && task.point > 0 && (
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}> 
                  <Iconify icon="solar:medal-ribbons-star-bold" />
                  <Typography variant="caption">{task.point} points</Typography>
                </Box>
              )}
            </Stack>

            {displaySettings.showDueDate && task.endDate && (
              <Stack direction="row" alignItems="center" spacing={1}>
                <Iconify icon="solar:calendar-date-bold" />
                <Typography variant="caption">
                  {formatDate(task.endDate)}
                </Typography>
              </Stack>
            )}

            {collaborators.length > 0 && (
              <Stack direction="row" alignItems="center" spacing={1}>        
                <AvatarGroup
                  max={3}
                  sx={{
                    '& .MuiAvatar-root': {
                      width: 24,
                      height: 24,
                      fontSize: '0.75rem',
                      border: (theme) => `solid 1px ${theme.palette.background.paper}`,
                    },
                  }}
                >
                  {collaborators.map((collaborator) => (
                    <Tooltip
                      key={collaborator.id}
                      title={`${collaborator.firstName} ${collaborator.lastName}`}
                      arrow
                      placement="top"
                    >
                      <Avatar
                        alt={`${collaborator.firstName} ${collaborator.lastName}`}
                        sx={{
                          bgcolor: (theme) => theme.palette.primary.main,    
                          color: (theme) => theme.palette.primary.contrastText,
                        }}
                      >
                        {collaborator.initials}
                      </Avatar>
                    </Tooltip>
                  ))}
                </AvatarGroup>
                {collaborators.length > 3 && (
                  <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                    +{collaborators.length - 3}
                  </Typography>
                )}
              </Stack>
            )}

            <Stack direction="row" justifyContent="flex-end">
              <IconButton
                onClick={openDetails.onTrue}
                sx={{
                  width: 32,
                  height: 32,
                  p: 0,
                  '&:hover': { bgcolor: 'action.hover' },
                }}
              >
                <Iconify icon="eva:more-horizontal-fill" />
              </IconButton>
            </Stack>
          </Stack>

          <Tooltip title="Delete task">
            <IconButton
              size="small"
              onClick={() => onDeleteTask(task.id)}
              sx={{
                position: 'absolute',
                right: 8,
                top: 8,
                color: 'grey.500',
                '&:hover': { color: 'error.main' },
              }}
            >
              <Iconify icon="eva:trash-2-outline" width={20} />
            </IconButton>
          </Tooltip>

          <Popover
            open={Boolean(anchorElColor)}
            anchorEl={anchorElColor}
            onClose={handleCloseColorPicker}
            anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}        
            transformOrigin={{ vertical: 'top', horizontal: 'left' }}        
            PaperProps={{
              sx: {
                p: 1,
                width: 180,
              },
            }}
          >
            <Stack direction="row" spacing={0.5} sx={{ p: 0.5 }}>
              {COLORS.map((color) => (
                <IconButton
                  key={color}
                  size="small"
                  onClick={() => handleClickColor(color)}
                  sx={{
                    p: 0,
                    width: 24,
                    height: 24,
                    bgcolor: color || 'background.paper',
                    border: (theme) => `solid 1px ${theme.palette.divider}`, 
                    '&:hover': { bgcolor: color ? alpha(color, 0.8) : 'background.paper' },
                    ...(color === '' && {
                      '&:after': {
                        content: "'×'",
                        color: 'text.disabled',
                        fontSize: 16,
                        fontWeight: 'bold',
                        lineHeight: 0,
                      },
                    }),
                  }}
                >
                  {task.color === color && color !== '' && (
                    <Iconify icon="eva:checkmark-fill" sx={{ width: 16, height: 16, color: 'white' }} />
                  )}
                </IconButton>
              ))}
            </Stack>
          </Popover>

          <KanbanDetails
            task={task}
            project={project}
            openDetails={openDetails.value}
            onCloseDetails={openDetails.onFalse}
            onUpdateTask={onUpdateTask}
            onDeleteTask={onDeleteTask}
          />
        </Paper>
      )}
    </Draggable>
  );
}