import { useCallback } from 'react';
import { Droppable, Draggable } from '@hello-pangea/dnd';

import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import { alpha } from '@mui/material/styles';
import Box from '@mui/material/Box';

import { useBoolean } from '../../../hooks';

import {
  clearColumn,
  updateColumn,
} from '../../api/kanban';

import Iconify from '@/shared/components/iconify/iconify';
import {useSnackbar}   from '@/shared/components/snackbar';

import { IKanbanTask, IKanbanColumn } from '@/shared/types/kanban';
import { ITaskItem } from '@/contexts/types/tasks';
import { Project } from '@/contexts/types/Project';

import KanbanTaskAdd from './kanban-task-add';
import KanbanTaskItem from './kanban-task-item';
import KanbanColumnToolBar from './kanban-column-tool-bar';
import { axiosInstance} from '@/utils/axios';

// ----------------------------------------------------------------------

type DisplaySettings = {
  showPriority: boolean;
  showDueDate: boolean;
  showAssignee: boolean;
  showStatus: boolean;
  showType: boolean;
  showPoints: boolean;
};

type KanbanColumnProps = {
  column: IKanbanColumn;
  index: number;
  projectId: number;
  project: Project;
  onUpdateColumn: (columnId: number, column: Partial<IKanbanColumn>) => void;
  onUpdateTask: (taskId: number, task: Partial<ITaskItem>) => void;
  onDeleteColumn: (columnId: number) => void;
  onUpdateColumnColor: (columnId: number, color: string) => void;
  onAddTask: (columnId: number, taskData: Partial<ITaskItem>) => Promise<void>;
  displaySettings: DisplaySettings;
  onDeleteTask: (taskId: number) => Promise<void>;
};

interface TaskData {
  name: string;
  tags?: string[];
}

export default function KanbanColumn({ column, index, projectId, project, onUpdateColumn, onUpdateTask, onDeleteColumn, onUpdateColumnColor, onAddTask, displaySettings, onDeleteTask }: KanbanColumnProps) {
  const { enqueueSnackbar } = useSnackbar();

  const openAddTask = useBoolean();

  const tasks = column.tasks || [];

  const handleUpdateColumn = useCallback(
    async (columnName: string) => {
      try {
        if (column.name !== columnName) {
          await axiosInstance.put(
            `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/kanban-columns/${column.id}`,
            { name: columnName }
          );
          enqueueSnackbar('Update success!');
        }
      } catch (error) {
        console.error(error);
        enqueueSnackbar('Update failed!', { variant: 'error' });
      }
    },
    [column.id, column.name, enqueueSnackbar]
  );

  const handleClearColumn = useCallback(async () => {
    try {
      clearColumn(column.id.toString());
    } catch (error) {
      console.error(error);
    }
  }, [column.id]);

  const handleDeleteColumn = useCallback(async () => {
    try {
      onDeleteColumn(column.id);
    } catch (error) {
      console.error(error);
      enqueueSnackbar('Delete failed!', { variant: 'error' });
    }
  }, [column.id, onDeleteColumn, enqueueSnackbar]);

  const handleAddTask = useCallback(
    async (taskData: { name: string; tags: string[] }) => {
      try {
        const email = localStorage.getItem('email');
        const agencyId = localStorage.getItem('selectedAgency');

        if (!email || !agencyId) {
          throw new Error('User email or agency not found');
        }

        const managerResponse = await axiosInstance.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/${email}/${agencyId}`
        );

        const managerId = managerResponse.data.id;

        const payload = {
          name: taskData.name,
          description: '',
          status: column.name,
          priority: 'LOW',
          type: 'FEATURE',
          point: 1,
          managerId: managerId,
          projectId: projectId,
          tags: taskData.tags,
          endDate: new Date(Date.now() + 86400000).toISOString(),
        };

        await axiosInstance.post(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/add`,
          payload
        );

        // Fetch updated column data
        const updatedColumnResponse = await axiosInstance.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/${projectId}/kanban-columns`
        );
        
        // Update the column with new data
        onUpdateColumn(column.id, updatedColumnResponse.data.find((col: any) => col.id === column.id));
        
        openAddTask.onFalse();
        enqueueSnackbar('Task created successfully!');
      } catch (error) {
        console.error('Task creation error:', error);
        enqueueSnackbar('Failed to create task', { variant: 'error' });
      }
    }, 
    [projectId, column, onUpdateColumn, openAddTask, enqueueSnackbar]
  );

  const handleUpdateTask = useCallback(async (taskData: IKanbanTask) => {
    try {
      const { id, name, description, status, priority } = taskData;
      onUpdateTask(id, { name, description, status, priority });
    } catch (error) {
      console.error(error);
    }
  }, [onUpdateTask]);

  const handleDeleteTask = useCallback(
    async (taskId: number) => {
      try {
        // Call the delete API
        await axiosInstance.delete(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/delete/${taskId}`
        );

        // Update the UI immediately by removing the task from the column
        const updatedTasks = column.tasks.filter(task => task.id !== taskId);
        onUpdateColumn(column.id, {
          ...column,
          tasks: updatedTasks
        });

        enqueueSnackbar('Task deleted successfully!', {
          variant: 'success',
        });
      } catch (error) {
        console.error('Failed to delete task:', error);
        enqueueSnackbar('Failed to delete task', { variant: 'error' });
      }
    },
    [column.id, column.tasks, onUpdateColumn, enqueueSnackbar]
  );

  const handleUpdateColumnColor = useCallback(
    (color: string) => {
      onUpdateColumnColor(column.id, color);
    },
    [column.id, onUpdateColumnColor]
  );



  const renderAddTask = (
    <Stack
      spacing={2}
      sx={{
        pb: 3,
        px: 2,
      }}
    >
      {openAddTask.value && (
        <Box sx={{ width: '90%', mx: 'auto' }}>
          <KanbanTaskAdd
            status={column.name}
            onAddTask={handleAddTask}
            onCloseAddTask={openAddTask.onFalse}
          />
        </Box>
      )}

      <Button
        fullWidth
        size="large"
        color="inherit"
        startIcon={
          <Iconify
            icon={openAddTask.value ? 'solar:close-circle-broken' : 'mingcute:add-line'}
            width={18}
            sx={{ mr: -0.5 }}
          />
        }
        onClick={openAddTask.onToggle}
        sx={{ fontSize: 14 }}
      >
        {openAddTask.value ? 'Close' : 'Add Task'}
      </Button>
    </Stack>
  );

  return (
    <Draggable draggableId={column.id.toString()} index={index}>
      {(provided) => (
        <Paper
          {...provided.draggableProps}
          ref={provided.innerRef}
          sx={{
            width: 1,
            minHeight: 'auto',
            bgcolor: (theme) => alpha(column.color || theme.palette.grey[500], 0.24),
            '&:hover': { boxShadow: 'none' },
          }}
        >
          <Stack sx={{ minHeight: 'auto' }}>
            <KanbanColumnToolBar
              columnName={column.name}
              color={column.color}
              onDelete={handleDeleteColumn}
              onClear={handleClearColumn}
              onUpdateColumn={handleUpdateColumn}
              onUpdateColor={handleUpdateColumnColor}
            />

            <Droppable droppableId={column.id.toString()}>
              {(dropProvided) => (
                <Stack
                  ref={dropProvided.innerRef}
                  {...dropProvided.droppableProps}
                  spacing={2}
                  sx={{
                    p: 2,
                    flexGrow: 0,
                    minHeight: 'auto',
                    overflow: 'hidden',
                    overflowY: 'auto',
                  }}
                >
                  {tasks.map((task, index) => (
                    <KanbanTaskItem
                      key={task.id}
                      index={index}
                      task={task}
                      project={project}
                      displaySettings={displaySettings}
                      onUpdateTask={(updatedTask) => onUpdateTask(updatedTask.id, updatedTask)}
                      onDeleteTask={() => onDeleteTask(task.id)}
                    />
                  ))}
                  {dropProvided.placeholder}
                </Stack>
              )}
            </Droppable>

            <Stack
              spacing={2}
              sx={{
                pb: 3,
                px: 2,
              }}
            >
              {openAddTask.value && (
                <Box sx={{ width: '90%', mx: 'auto' }}>
                  <KanbanTaskAdd
                    status={column.name}
                    onAddTask={handleAddTask}
                    onCloseAddTask={openAddTask.onFalse}
                  />
                </Box>
              )}

              <Button
                fullWidth
                size="large"
                color="inherit"
                startIcon={
                  <Iconify
                    icon={openAddTask.value ? 'solar:close-circle-broken' : 'mingcute:add-line'}
                    width={18}
                    sx={{ mr: -0.5 }}
                  />
                }
                onClick={openAddTask.onToggle}
                sx={{ fontSize: 14 }}
              >
                {openAddTask.value ? 'Close' : 'Add Task'}
              </Button>
            </Stack>
          </Stack>
        </Paper>
      )}
    </Draggable>
  );
}
