'use client';

import { useCallback, useEffect, useState } from 'react';
import { DragDropContext, Droppable, DropResult } from '@hello-pangea/dnd';
import {
  Stack,
  Container,
  Typography,
  FormControl,
  InputLabel,
  Select,
  Snackbar,
  SnackbarContent,
  InputAdornment,
  TextField,
  IconButton,
} from '@mui/material';
import { alpha } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import Iconify from '@/shared/components/iconify';

import Scrollbar from '@/shared/components/scrollbar';
import EmptyContent from '@/shared/components/empty-content';
import { IKanbanColumn } from '@/shared/types/kanban';
import { changeTaskStatus, getAllKanbanColumns, reorderKanbanColumns } from '@/shared/api/kanban';
import {

  Project
} from "@/contexts/types/Project";
import KanbanColumn from '../kanban-column';
import KanbanColumnAdd from '../kanban-column-add';
import { KanbanColumnSkeleton } from '../kanban-skeleton';
import { axiosInstance } from '@/utils/axios';
import KanbanDisplaySettings from '../kanban-display-settings';
import { filterAndSortTasks } from '../utils/task-filters';
import KanbanOverview from './kanban-overview';
import { ITaskItem } from '@/contexts/types/tasks';

// Define the display settings type
type DisplaySettings = {
  showPriority: boolean;
  showDueDate: boolean;
  showType: boolean;
  showTags: boolean;
  showPoints: boolean;
  showAssignee: boolean;
  showStatus: boolean;
};

type SortDirection = 'asc' | 'desc';

type Props = {
  projectId?: number;  
};

export default function KanbanView({ projectId }: Props) {
  const [columns, setColumns] = useState<IKanbanColumn[]>([]);
  const [projects, setProjects] = useState<Project[]>([]);
  const [selectedProjectId, setSelectedProjectId] = useState<string>(projectId?.toString() || '');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error'>('success');
  // Initialize display settings with default values
  const [displaySettings, setDisplaySettings] = useState<DisplaySettings>({
    showPriority: true,
    showDueDate: true,
    showType: true,
    showTags: true,
    showPoints: true,
    showAssignee: true,
    showStatus: true,
  });

  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [filterAnchorEl, setFilterAnchorEl] = useState<null | HTMLElement>(null);
  const [sortAnchorEl, setSortAnchorEl] = useState<null | HTMLElement>(null);
  const [filters, setFilters] = useState({
    type: 'all',
    status: 'all',
    priority: 'all',
    assignee: 'all'
  });
  const [sortConfig, setSortConfig] = useState<{
    field: string;
    direction: SortDirection;
  }>({
    field: '',
    direction: 'asc'
  });
  const [showOverview, setShowOverview] = useState(false);

  const handleOpenMenu = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleCloseMenu = () => {
    setAnchorEl(null);
  };

  const handleToggleSetting = (setting: string) => {
    setDisplaySettings((prev) => ({
      ...prev,
      [setting]: !prev[setting as keyof typeof displaySettings],
    }));
  };

  const handleOpenFilters = (event: React.MouseEvent<HTMLElement>) => {
    setFilterAnchorEl(event.currentTarget);
  };

  const handleCloseFilters = () => {
    setFilterAnchorEl(null);
  };

  const handleOpenSort = (event: React.MouseEvent<HTMLElement>) => {
    setSortAnchorEl(event.currentTarget);
  };

  const handleCloseSort = () => {
    setSortAnchorEl(null);
  };

  const handleFilterChange = (filterType: string, value: string) => {
    setFilters(prev => ({
      ...prev,
      [filterType]: value
    }));
  };

  const handleSortChange = (field: string) => {
    setSortConfig(prev => {
      const newDirection: SortDirection = prev.field === field ?
        (prev.direction === 'asc' ? 'desc' : 'asc') :
        'asc';
      return { field, direction: newDirection };
    });
  };

  const getFilteredAndSortedTasks = (columnTasks: ITaskItem[]) => {
    return filterAndSortTasks(columnTasks, filters, sortConfig);
  };

  // Fetch user's projects
  useEffect(() => {
    setLoading(true);
    const email = localStorage.getItem("email");
    const agencyId = localStorage.getItem("selectedAgency");

    if (!email || !agencyId) {
      setError(true);
      setLoading(false);
      return;
    }

    axiosInstance.get(
      `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/${email}/${agencyId}`
    )
      .then((accountAgencyResponse) => {
        const userId = accountAgencyResponse.data.id;
        const role = accountAgencyResponse.data.role.name;

        const queryParams = new URLSearchParams({
          userId: userId.toString(),
          role: role,
          agencyId: agencyId,
        });

        return axiosInstance.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/get/projects/for/user?${queryParams}`
        );
      })
      .then((projectResponse) => {
        setProjects(projectResponse.data);
        // Only set selectedProjectId if it wasn't already set from props
        if (!selectedProjectId) {
          setSelectedProjectId(projectResponse.data[0]?.id?.toString() || '');
        }
      })
      .catch((err) => {
        console.error("Failed to fetch projects:", err);
        // Remove error message display, just set empty projects array
        setProjects([]);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);  // Remove selectedProjectId from dependencies to prevent loop

  // Fetch Kanban columns when project is selected
  useEffect(() => {
    if (!selectedProjectId) return;
    
    setLoading(true);
    axiosInstance.get(
      `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/${selectedProjectId}/kanban-columns`
    )
      .then((response) => {
        const columnsWithSortedTasks = response.data.map((column: IKanbanColumn) => ({
          ...column,
          tasks: column.tasks
            .filter(task => !task.deletedAt)
            .sort((a, b) => {
              // Sort by orderIndex if available, fallback to id if not
              if (a.orderIndex !== undefined && b.orderIndex !== undefined) {
                return a.orderIndex - b.orderIndex;
              }
              return 0;
            })
        }));
        
        setColumns(columnsWithSortedTasks.sort((a: IKanbanColumn, b: IKanbanColumn) => 
          a.orderIndex - b.orderIndex
        ));
      })
      .catch((err) => {
        console.error("Failed to fetch Kanban columns:", err);
        setError(true);
        setSnackbarMessage("Failed to fetch Kanban columns");
        setSnackbarSeverity('error');
        setSnackbarOpen(true);
      })
      .finally(() => {
        setLoading(false);
      });
  }, [selectedProjectId]);

  const onDragEnd = useCallback(
    async ({ source, destination, draggableId, type }: DropResult) => {
      if (!destination || !selectedProjectId) return;

      if (type === 'COLUMN') {
        const reorderedColumns = Array.from(columns);
        const [movedColumn] = reorderedColumns.splice(source.index, 1);
        reorderedColumns.splice(destination.index, 0, movedColumn);

        setColumns(reorderedColumns);

        const columnIds = reorderedColumns.map((column) => column.id);
        axiosInstance.put(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/${selectedProjectId}/kanban-columns/reorder`,
          { columnIds }
        )
          .then(() => {
            setSnackbarMessage('Columns reordered successfully!');
            setSnackbarSeverity('success');
            setSnackbarOpen(true);
          })
          .catch(() => {
            setSnackbarMessage('An error occurred during reordering');
            setSnackbarSeverity('error');
            setSnackbarOpen(true);
          });
      } else {
        try {
          const taskId = parseInt(draggableId, 10);
          const newColumnId = parseInt(destination.droppableId, 10);
          const sourceColumnId = parseInt(source.droppableId, 10);

          const newColumns = [...columns];

          if (sourceColumnId === newColumnId) {
            // Same column - reorder tasks
            const column = newColumns.find(col => col.id === newColumnId);
            if (!column) throw new Error('Column not found');

            const [movedTask] = column.tasks.splice(source.index, 1);
            column.tasks.splice(destination.index, 0, movedTask);

            setColumns(newColumns);

            const newTaskIds = column.tasks.map(task => task.id);


            const response = await axiosInstance.put(
              `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/kanban-columns/${newColumnId}/tasks/reorder`,
              newTaskIds,
              {
                headers: {
                  'Content-Type': 'application/json'
                }
              }
            );

          } else {
            const sourceColumn = newColumns.find(col => col.id === sourceColumnId);
            const destColumn = newColumns.find(col => col.id === newColumnId);
            
            if (!sourceColumn || !destColumn) throw new Error('Column not found');

            const [movedTask] = sourceColumn.tasks.splice(source.index, 1);
            
            destColumn.tasks.splice(destination.index, 0, {
              ...movedTask,
              status: destColumn.name
            });

            setColumns(newColumns);

            try {
              await axiosInstance.put(
                `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/tasks/${taskId}/move`,
                null,
                {
                  params: {
                    newColumnId,
                    newOrderIndex: destination.index
                  }
                }
              );

              const newTaskIds = destColumn.tasks.map(task => task.id);
              await axiosInstance.put(
                `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/kanban-columns/${newColumnId}/tasks/reorder`,
                newTaskIds
              );
            } catch (error) {
              setColumns(columns);
              throw error; 
            }
          }

          setSnackbarMessage('Task moved successfully');
          setSnackbarSeverity('success');
          setSnackbarOpen(true);
        } catch (error) {
          console.error('Failed to move task:', error);
          setColumns(columns); 
          setSnackbarMessage('Failed to move task');
          setSnackbarSeverity('error');
          setSnackbarOpen(true);
        }
      }
    },
    [selectedProjectId, columns]
  );

  const handleColumnAdded = useCallback((columnName: string) => {
    if (!selectedProjectId) {
      setSnackbarMessage('Please select a project first');
      setSnackbarSeverity('error');
      setSnackbarOpen(true);
      return;
    }

    axiosInstance.post(
      `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/${selectedProjectId}/kanban-columns`,
      {
        name: columnName,
      }
    )
      .then((response) => {
        setColumns((prevColumns) => [...prevColumns, response.data]);
        setSnackbarMessage('Column added successfully');
        setSnackbarSeverity('success');
        setSnackbarOpen(true);
      })
      .catch((error) => {
        console.error('Failed to add column:', error);
        setSnackbarMessage('Failed to add column');
        setSnackbarSeverity('error');
        setSnackbarOpen(true);
      });
  }, [selectedProjectId, columns.length]);

  const handleUpdateColumn = useCallback((columnId: number, column: Partial<IKanbanColumn>) => {
    setColumns(prevColumns => 
      prevColumns.map(col => 
        col.id === columnId 
          ? { ...col, ...column }
          : col
      )
    );
  }, []);

  const handleUpdateTask = (updatedTask: any) => {
    // Update the task in columns
    setColumns((prevColumns) =>
      prevColumns.map((column) => ({
        ...column,
        tasks: column.tasks.map((task) =>
          task.id === updatedTask.id ? { ...task, ...updatedTask } : task
        ),
      }))
    );
  };

  const handleDeleteColumn = useCallback(async (columnId: number) => {
    try {
      await axiosInstance.delete(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/${selectedProjectId}/kanban-columns/${columnId}`
      );
      
      setColumns((prevColumns) => prevColumns.filter((column) => column.id !== columnId));
      
      setSnackbarMessage('Column deleted successfully');
      setSnackbarSeverity('success');
      setSnackbarOpen(true);
    } catch (error) {
      console.error('Failed to delete column:', error);
      setSnackbarMessage('Failed to delete column');
      setSnackbarSeverity('error');
      setSnackbarOpen(true);
    }
  }, [selectedProjectId]);

  const handleUpdateColumnColor = useCallback((columnId: number, color: string) => {
    setColumns((prevColumns) =>
      prevColumns.map((column) =>
        column.id === columnId ? { ...column, color } : column
      )
    );
    
    setSnackbarMessage('Column color updated');
    setSnackbarSeverity('success');
    setSnackbarOpen(true);
  }, []);

  const renderSkeleton = (
    <Stack direction="row" alignItems="flex-start" spacing={3}>
      {[...Array(4)].map((_, index) => (
        <KanbanColumnSkeleton key={index} index={index} />
      ))}
    </Stack>
  );

  const getProcessedTasks = (columnTasks: ITaskItem[]) => {
    if (!columnTasks) return [];
    
    let processedTasks = [...columnTasks].filter(task => {
      const searchLower = searchQuery.toLowerCase();
      const nameMatch = task.name.toLowerCase().includes(searchLower);
      const descriptionMatch = task.description?.toLowerCase().includes(searchLower);
      const typeMatch = task.type.toLowerCase().includes(searchLower);
      const priorityMatch = task.priority.toLowerCase().includes(searchLower);
      
      if (!searchQuery) return true;
      
      return nameMatch || descriptionMatch || typeMatch || priorityMatch;
    });

    processedTasks = processedTasks.filter(task => {
      const typeMatch = filters.type === 'all' || task.type === filters.type;
      const statusMatch = filters.status === 'all' || task.status === filters.status;
      const priorityMatch = filters.priority === 'all' || task.priority === filters.priority;
      const assigneeMatch = filters.assignee === 'all' || 
        (task.collaboratorIds && task.collaboratorIds.includes(Number(filters.assignee)));

      return typeMatch && statusMatch && priorityMatch && assigneeMatch;
    });

    return processedTasks.sort((a, b) => {
      let comparison = 0;

      switch (sortConfig.field) {
        case 'dueDate':
        case 'endDate':
          const dateA = new Date(a.endDate || '').getTime();
          const dateB = new Date(b.endDate || '').getTime();
          comparison = dateA - dateB;
          break;
        case 'priority': {
          const priorityOrder = { HIGH: 3, MEDIUM: 2, LOW: 1 } as const;
          comparison = (priorityOrder[a.priority as keyof typeof priorityOrder] || 0) - 
                       (priorityOrder[b.priority as keyof typeof priorityOrder] || 0);
          break;
        }
        case 'status': {
          const statusOrder = { 'TO DO': 1, 'IN PROGRESS': 2, 'DONE': 3 } as const;
          comparison = (statusOrder[a.status as keyof typeof statusOrder] || 0) - 
                       (statusOrder[b.status as keyof typeof statusOrder] || 0);
          break;
        }
      }

      return sortConfig.direction === 'asc' ? comparison : -comparison;
    });
  };

  const handleAddTask = useCallback(async (columnId: number, taskData: Partial<ITaskItem>) => {
    try {
      // Create task
      await axiosInstance.post(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/tasks/${columnId}`,
        taskData
      );
      
      // Fetch updated column data to get the new task with correct ID
      const response = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/${selectedProjectId}/kanban-columns`
      );
      
      const columnsWithSortedTasks = response.data.map((column: IKanbanColumn) => ({
        ...column,
        tasks: column.tasks
          .filter(task => !task.deletedAt)
          .sort((a, b) => {
            if (a.orderIndex !== undefined && b.orderIndex !== undefined) {
              return a.orderIndex - b.orderIndex;
            }
            return 0;
          })
      }));
      
      setColumns(columnsWithSortedTasks.sort((a: IKanbanColumn, b: IKanbanColumn) => 
        a.orderIndex - b.orderIndex
      ));

    } catch (error) {
      console.error('Failed to add task:', error);
    }
  }, [selectedProjectId]);

  const handleDeleteTask = useCallback(async (taskId: number) => {
    // First show confirmation dialog
    if (!window.confirm('Are you sure you want to delete this task?')) {
      return;
    }

    try {
      await axiosInstance.delete(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/delete/${taskId}`
      );
      
      setColumns(prevColumns =>
        prevColumns.map(col => ({
          ...col,
          tasks: col.tasks.filter(task => task.id !== taskId)
        }))
      );

      setSnackbarMessage('Task deleted successfully');
      setSnackbarSeverity('success');
      setSnackbarOpen(true);
    } catch (error) {
      console.error('Failed to delete task:', error);
      setSnackbarMessage('Failed to delete task');
      setSnackbarSeverity('error');
      setSnackbarOpen(true);
    }
  }, []);

  if (showOverview) {
    return <KanbanOverview tasks={columns.flatMap(column => column.tasks || [])} onBack={() => setShowOverview(false)} />;
  }

  return (
    <Box
      sx={{
        width: '100%',
        height: '100%',
        position: 'relative',
        overflow: 'hidden',
      }}
    >
      <Container
        maxWidth={false}
        disableGutters
        sx={{ 
          p: 0,
          m: 0,
          width: '100%',
          position: 'relative',
          left: 0,
        }}
      >
        <Stack spacing={2} sx={{ mb: 3 }}>
          <Stack direction="row" alignItems="center" justifyContent="space-between">
            <Typography variant="h4">Kanban</Typography>

            <Stack direction="row" spacing={2} alignItems="center">
              <Stack direction="row" spacing={1} alignItems="center">
                <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                  Select Project
                </Typography>
                <Select
                  value={selectedProjectId || ''}
                  onChange={(e) => setSelectedProjectId(e.target.value)}
                  size="small"
                  sx={{ minWidth: 180 }}
                >
                  {projects.map((project) => (
                    <MenuItem key={project.id} value={project.id}>
                      {project.name}
                    </MenuItem>
                  ))}
                </Select>
              </Stack>

              <Button
                color="inherit"
                onClick={() => setShowOverview(true)}
                endIcon={<Iconify icon="eva:pie-chart-2-fill" />}
                sx={{ 
                  bgcolor: 'background.neutral',
                  '&:hover': { bgcolor: 'background.neutral' }
                }}
              >
                View Overview
              </Button>

              <Button
                color="inherit"
                onClick={handleOpenMenu}
                endIcon={<Iconify icon="eva:settings-2-outline" />}
              >
                Display Options
              </Button>
            </Stack>
          </Stack>

          <Stack direction="row" spacing={2} alignItems="center">
            <TextField
              size="small"
              placeholder="Search tasks..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              sx={{ flexGrow: 1 }}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <Iconify icon="eva:search-fill" sx={{ color: 'text.disabled' }} />
                  </InputAdornment>
                ),
              }}
            />

            <Button
              color="inherit"
              onClick={handleOpenFilters}
              endIcon={<Iconify icon="eva:funnel-fill" />}
            >
              Filters
            </Button>

            <Select
              size="small"
              value={sortConfig.field}
              onChange={(e) => handleSortChange(e.target.value)}
              sx={{ minWidth: 120 }}
              startAdornment={
                <IconButton
                  size="small"
                  onClick={() => handleSortChange(sortConfig.field)}
                >
                  <Iconify 
                    icon={sortConfig.direction === 'asc' ? 'eva:arrow-up-fill' : 'eva:arrow-down-fill'}
                  />
                </IconButton>
              }
            >
              <MenuItem value="createdAt">Created Date</MenuItem>
              <MenuItem value="endDate">Due Date</MenuItem>
              <MenuItem value="priority">Priority</MenuItem>
              <MenuItem value="status">Status</MenuItem>
            </Select>
          </Stack>
        </Stack>

        {/* Filters Menu */}
        <Menu
          anchorEl={filterAnchorEl}
          open={Boolean(filterAnchorEl)}
          onClose={() => setFilterAnchorEl(null)}
        >
          <Box sx={{ p: 2, width: 280 }}>
            <Stack spacing={2}>
              <FormControl fullWidth size="small">
                <InputLabel>Type</InputLabel>
                <Select
                  value={filters.type}
                  onChange={(e) => handleFilterChange('type', e.target.value)}
                  label="Type"
                >
                  <MenuItem value="all">All Types</MenuItem>
                  <MenuItem value="BUG">Bug</MenuItem>
                  <MenuItem value="FEATURE">Feature</MenuItem>
                  <MenuItem value="IMPROVEMENT">Improvement</MenuItem>
                </Select>
              </FormControl>

              <FormControl fullWidth size="small">
                <InputLabel>Status</InputLabel>
                <Select
                  value={filters.status}
                  onChange={(e) => handleFilterChange('status', e.target.value)}
                  label="Status"
                >
                  <MenuItem value="all">All Status</MenuItem>
                  <MenuItem value="TO DO">To Do</MenuItem>
                  <MenuItem value="IN PROGRESS">In Progress</MenuItem>
                  <MenuItem value="DONE">Done</MenuItem>
                </Select>
              </FormControl>

              <FormControl fullWidth size="small">
                <InputLabel>Priority</InputLabel>
                <Select
                  value={filters.priority}
                  onChange={(e) => handleFilterChange('priority', e.target.value)}
                  label="Priority"
                >
                  <MenuItem value="all">All Priorities</MenuItem>
                  <MenuItem value="HIGH">High</MenuItem>
                  <MenuItem value="MEDIUM">Medium</MenuItem>
                  <MenuItem value="LOW">Low</MenuItem>
                </Select>
              </FormControl>
            </Stack>
          </Box>
        </Menu>

        {/* Sort Menu */}
        <Menu
          anchorEl={sortAnchorEl}
          open={Boolean(sortAnchorEl)}
          onClose={() => setSortAnchorEl(null)}
        >
          <MenuItem 
            onClick={() => {
              handleSortChange('endDate');
              setSortAnchorEl(null);
            }}
            sx={{ 
              display: 'flex', 
              justifyContent: 'space-between',
              width: 200
            }}
          >
            Due Date
            {(sortConfig.field === 'endDate' || sortConfig.field === 'dueDate') && (
              <Iconify 
                icon={sortConfig.direction === 'asc' ? 'eva:arrow-up-fill' : 'eva:arrow-down-fill'}
              />
            )}
          </MenuItem>
          <MenuItem 
            onClick={() => {
              handleSortChange('priority');
              setSortAnchorEl(null);
            }}
            sx={{ 
              display: 'flex', 
              justifyContent: 'space-between',
              width: 200
            }}
          >
            Priority
            {sortConfig.field === 'priority' && (
              <Iconify 
                icon={sortConfig.direction === 'asc' ? 'eva:arrow-up-fill' : 'eva:arrow-down-fill'}
              />
            )}
          </MenuItem>
          <MenuItem 
            onClick={() => {
              handleSortChange('status');
              setSortAnchorEl(null);
            }}
            sx={{ 
              display: 'flex', 
              justifyContent: 'space-between',
              width: 200
            }}
          >
            Status
            {sortConfig.field === 'status' && (
              <Iconify 
                icon={sortConfig.direction === 'asc' ? 'eva:arrow-up-fill' : 'eva:arrow-down-fill'}
              />
            )}
          </MenuItem>
        </Menu>

        {/* Display Options Menu */}
        <Menu
          anchorEl={anchorEl}
          open={Boolean(anchorEl)}
          onClose={handleCloseMenu}
        >
          <Box sx={{ p: 2, width: 220 }}>
            <Stack spacing={1.5}>
              <FormControlLabel
                control={
                  <Checkbox
                    checked={displaySettings.showPriority}
                    onChange={() => handleToggleSetting('showPriority')}
                  />
                }
                label="Show Priority"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    checked={displaySettings.showDueDate}
                    onChange={() => handleToggleSetting('showDueDate')}
                  />
                }
                label="Show Due Date"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    checked={displaySettings.showType}
                    onChange={() => handleToggleSetting('showType')}
                  />
                }
                label="Show Type"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    checked={displaySettings.showTags}
                    onChange={() => handleToggleSetting('showTags')}
                  />
                }
                label="Show Tags"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    checked={displaySettings.showPoints}
                    onChange={() => handleToggleSetting('showPoints')}
                  />
                }
                label="Show Points"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    checked={displaySettings.showAssignee}
                    onChange={() => handleToggleSetting('showAssignee')}
                  />
                }
                label="Show Assignee"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    checked={displaySettings.showStatus}
                    onChange={() => handleToggleSetting('showStatus')}
                  />
                }
                label="Show Status"
              />
            </Stack>
          </Box>
        </Menu>

        {loading && renderSkeleton}

        {columns.length === 0 ? (
          <EmptyContent
            filled
            title="No Data"
            sx={{
              py: 10,
              maxHeight: { md: 480 },
            }}
          />
        ) : (
          <DragDropContext onDragEnd={onDragEnd}>
            <Droppable droppableId="kanban" direction="horizontal" type="COLUMN">
              {(provided) => (
                <Stack
                  ref={provided.innerRef}
                  {...provided.droppableProps}
                  spacing={2}
                  direction="row"
                  alignItems="flex-start"
                  sx={{
                    height: 'calc(100% - 32px)',
                    overflowY: 'hidden',
                    overflowX: 'auto',
                    p: 0,
                    m: 0,
                    position: 'relative',
                    left: 0,
                    '& > *': {
                      minWidth: 280,
                      maxWidth: 300,
                    },
                    '& [data-rbd-droppable-id]': {
                      transform: 'none !important'
                    },
                    '& [data-rbd-draggable-context-id]': {
                      transform: 'none !important'
                    }
                  }}
                >
                  {columns.map((column, index) => {
                    const processedTasks = getProcessedTasks(column.tasks || []);
                    
                    return (
                      <KanbanColumn
                        key={`${column.id}-${sortConfig.field}-${sortConfig.direction}`}
                        index={index}
                        column={{
                          ...column,
                          tasks: processedTasks
                        }}
                        projectId={Number(selectedProjectId)}
                        project={projects.find(p => p.id === Number(selectedProjectId)) || {
                          id: 0,
                          name: '',
                          startDate: new Date(),
                          endDate: new Date(),
                          description: '',
                          type: '',
                          status: '',
                          itemState: '',
                          lastModification: new Date(),
                          tasks: [],
                          responsibleId: undefined,
                          collaboratorsIds: [],
                          clientId: undefined,
                          agencyId: undefined
                        }}
                        onUpdateColumn={handleUpdateColumn}
                        onUpdateTask={handleUpdateTask}
                        onDeleteColumn={handleDeleteColumn}
                        onUpdateColumnColor={handleUpdateColumnColor}
                        onAddTask={(columnId: number, taskData: Partial<ITaskItem>) => handleAddTask(columnId, taskData)}
                        onDeleteTask={handleDeleteTask}
                        displaySettings={displaySettings}
                      />
                    );
                  })}
                  {provided.placeholder}

                  <KanbanColumnAdd 
                    projectId={selectedProjectId} 
                    onColumnAdded={handleColumnAdded} 
                  />
                </Stack>
              )}
            </Droppable>
          </DragDropContext>
        )}
        <Snackbar
          open={snackbarOpen}
          autoHideDuration={3000}
          onClose={() => setSnackbarOpen(false)}
        >
          <SnackbarContent
            message={snackbarMessage}
            sx={{
              backgroundColor: snackbarSeverity === 'error' ? 'error.main' : 'success.main',
            }}
          />
        </Snackbar>
      </Container>
    </Box>
  );
}
