import { useState, useCallback, useEffect } from 'react';
import { useForm, Controller } from 'react-hook-form';
import * as Yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import axios from 'axios';
import { useSnackbar } from 'notistack';
import {
  Project,
} from "@/contexts/types/Project";
import Chip from '@mui/material/Chip';
import Grid from '@mui/material/Grid';
import Stack from '@mui/material/Stack';
import Drawer from '@mui/material/Drawer';
import Button from '@mui/material/Button';
import Avatar from '@mui/material/Avatar';
import Divider from '@mui/material/Divider';
import Tooltip from '@mui/material/Tooltip';
import TextField from '@mui/material/TextField';
import DialogContent from '@mui/material/DialogContent';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import Tab from '@mui/material/Tab';
import Tabs from '@mui/material/Tabs';
import { alpha, styled } from '@mui/material/styles';
import { LocalizationProvider, DatePicker } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { TabContext, TabPanel } from '@mui/lab';
import AttachFileIcon from '@mui/icons-material/AttachFile';
import { useBoolean } from '@/hooks';

import { ITaskItem } from '@/contexts/types/tasks';
import Iconify from '@/shared/components/iconify/iconify';
import Scrollbar from '@/shared/components/scrollbar';
import { formatDate } from '@/utils/format-time';

import KanbanInputName from './kanban-input-name';
import KanbanDetailsToolbar from './kanban-details-toolbar';
import KanbanContactsDialog from './kanban-contacts-dialog';
import KanbanDetailsPriority from './kanban-details-priority';
import KanbanDetailsAttachments from './kanban-details-attachments';
import KanbanDetailsCommentList from './kanban-details-comment-list';
import KanbanDetailsCommentInput from './kanban-details-comment-input';

import { endpoints } from '@/utils/axios';
import { PROJECT_API } from '@/config-global';
import { axiosInstance } from '@/utils/axios';
import TaskDetailsAttachments from '../add-task/task-details-attachments';
import Autocomplete from '@mui/material/Autocomplete';

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

type Props = {
  task: ITaskItem;
  openDetails: boolean;
  onCloseDetails: VoidFunction;
  //
  onUpdateTask: (task: ITaskItem) => void;
  onDeleteTask: (taskId: number) => void;
  project: Project;
};

const StyledLabel = styled("span")(({ theme }) => ({
  ...theme.typography.caption,
  width: 100,
  flexShrink: 0,
  color: theme.palette.text.secondary,
  fontWeight: theme.typography.fontWeightSemiBold,
}));
const NewTaskSchema = Yup.object().shape({
  name: Yup.string().required('Name is required'),
  description: Yup.string(),
  // Add other validation rules as needed
});

interface User {
  firstName: string;
  lastName: string;
}

interface Collaborator {
  id: number;
  user: User;
}

export default function KanbanDetails({
  task,
  openDetails,
  onCloseDetails,
  onUpdateTask,
  onDeleteTask,
  project,
}: Props) {
  const methods = useForm({
    resolver: yupResolver(NewTaskSchema),
    defaultValues: {
      name: task?.name || '',
      description: task?.description || '',
    }
  });

  const [taskName, setTaskName] = useState(task?.name || '');
  const [taskDescription, setTaskDescription] = useState(task?.description || '');
  const [priority, setPriority] = useState(task?.priority || 'LOW');
  const [endDate, setEndDate] = useState(task?.endDate ? new Date(task?.endDate) : null);
  const [showDatePicker, setShowDatePicker] = useState(false);
  const [taskMark, setTaskMark] = useState(task?.point || 0);
  const [type, setType] = useState(task?.type || 'BUG');
  const [status, setStatus] = useState(task?.status || 'TO DO');
  const [tabValue, setTabValue] = useState('attachments');
  const [attachments, setAttachments] = useState<any[]>(task?.attachments || []);
  const [uploadProgress, setUploadProgress] = useState<number>(0);
  const [taskCollaborators, setTaskCollaborators] = useState<Collaborator[]>([]);
  const [taskManager, setTaskManager] = useState<Collaborator | null>(null);
  const contacts = useBoolean();
  const [name, setName] = useState(task.name);
  const [tags, setTags] = useState<string[]>(task.tags || []);
  
  const { control } = methods;

  const { enqueueSnackbar } = useSnackbar();

  // API Functions copied from TaskDetails
  const updateTaskName = async (taskId: number, newName: string) => {
    try {
      const response = await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/name`,
        null,
        {
          params: { newName },
        }
      );
      onUpdateTask({
        ...task,
        name: newName
      });
    } catch (error) {
      console.error("Failed to update task name:", error);
      setTaskName(task.name);
    }
  };

  const updateTaskDate = async (taskId: number, newDate: Date) => {
    try {
      const response = await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/date`,
        null,
        {
          params: { endDate: newDate.toISOString().split('T')[0] },
        }
      );
      onUpdateTask({
        ...task,
        endDate: newDate.toISOString().split('T')[0]
      });
    } catch (error) {
      console.error("Failed to update task date:", error);
      setEndDate(new Date(task.endDate));
    }
  };

  const updateTaskPriority = async (taskId: number, newPriority: string) => {
    try {
      const response = await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/priority`,
        null,
        {
          params: { priority: newPriority },
        }
      );
      onUpdateTask({
        ...task,
        priority: newPriority
      });
    } catch (error) {
      console.error("Failed to update task priority:", error);
      setPriority(task.priority);
    }
  };

  const updateTaskPoint = async (taskId: number, newPoint: number) => {
    try {
      const response = await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/point`,
        null,
        {
          params: { number: newPoint },
        }
      );
      onUpdateTask({
        ...task,
        point: newPoint
      });
    } catch (error) {
      console.error("Failed to update task points:", error);
      setTaskMark(task.point);
    }
  };

  const updateTaskDescription = async (taskId: number, newDescription: string) => {
    try {
      await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/description`,
        newDescription,
        { headers: { 'Content-Type': 'text/plain' } }
      );
      
      if (task) {
        onUpdateTask({ ...task, description: newDescription });
      }
    } catch (error) {
      console.error("Failed to update task description:", error);
    }
  };

  const handleEditorChange = async (newDescription: string) => {
    setTaskDescription(newDescription);

    if (task) {
      await updateTaskDescription(task.id, newDescription);
    }
  };

  const updateTaskType = async (taskId: number, newType: string) => {
    try {
      const response = await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/type`,
        null,
        {
          params: { type: newType },
        }
      );
      onUpdateTask({
        ...task,
        type: newType
      });
    } catch (error) {
      console.error("Failed to update task type:", error);
      setType(task.type);
    }
  };

  const updateTask = async (taskId: number, updatedTaskData: any) => {
    try {
      const response = await axios.put(`${PROJECT_API}/${taskId}`, updatedTaskData);
      return response.data;
    } catch (error) {
      console.error('Failed to update task:', error);
      throw error;
    }
  };

  const updateTaskStatus = async (taskId: number, newStatus: string) => {
    try {
      const response = await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/status`,
        null,
        {
          params: { status: newStatus },
        }
      );
      onUpdateTask({
        ...task,
        status: newStatus
      });
    } catch (error) {
      console.error("Failed to update task status:", error);
      setStatus(task.status);
    }
  };

  // Handlers
  const handleChangeTaskName = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const newName = event.target.value;
    setTaskName(newName);
    if (task) {
      await updateTaskName(task.id, newName);
    }
  };

  const handleChangeStatus = async (newStatus: string) => {
    try {
      setStatus(newStatus);
      if (task) {
        await updateTaskStatus(task.id, newStatus);
      }
    } catch (error) {
      console.error('Failed to update status:', error);
      setStatus(task.status);
    }
  };
  const handleDateChange = async (newDate: Date | null) => {
    setEndDate(newDate);
    setShowDatePicker(false);
    if (task && newDate) {
      await updateTaskDate(task.id, newDate);
    }
  };

  const handleChangePriority = async (newPriority: string) => {
    setPriority(newPriority);
    if (task) {
      await updateTaskPriority(task.id, newPriority);
    }
  };

  const handleChangeType = async (newType: string) => {
    setType(newType);
    if (task) {
      await updateTaskType(task.id, newType);
    }
  };

  const handleChangeMark = async (newMark: number) => {
    setTaskMark(newMark);
    if (task) {
      await updateTaskPoint(task.id, newMark);
    }
  };

  const handleUpdateTask = async () => {
    if (!task) return;

    try {
      const updatedTaskData = {
        ...task,
        name,
        description: taskDescription,
        priority,
        endDate,
        type,
        status,
        point: taskMark,
        tags,
      };

      const updatedTask = await updateTask(task.id, updatedTaskData);
      onUpdateTask(updatedTask);
      onCloseDetails();
    } catch (error) {
      console.error('Failed to update task:', error);
    }
  };

  const handleTabChange = (event: React.SyntheticEvent, newValue: string) => {
    setTabValue(newValue);
  };

  const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await axios.post(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/attachments/upload/${task.id}`,
        formData,
        {
          onUploadProgress: (progressEvent) => {
            const progress = Math.round((progressEvent.loaded * 100) / (progressEvent.total || 1));
            setUploadProgress(progress);
          },
        }
      );

      // Update attachments list
      setAttachments((prevAttachments) => [...prevAttachments, response.data]);
      
      // Reset progress
      setUploadProgress(0);
      
      // Show success message
      enqueueSnackbar('File uploaded successfully!', { variant: 'success' });
    } catch (error) {
      console.error('Error uploading file:', error);
      setUploadProgress(0);
      // Show error message
      enqueueSnackbar('Failed to upload file', { variant: 'error' });
    }
  };

  const handleDownloadAttachment = async (attachmentId: number, fileName: string) => {
    try {
      const response = await axios.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/attachments/${attachmentId}/download`,
        { responseType: 'blob' }
      );

      // Create blob link to download
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', fileName);
      
      // Append to html link element page
      document.body.appendChild(link);
      
      // Start download
      link.click();
      
      // Clean up and remove the link
      link.parentNode?.removeChild(link);
    } catch (error) {
      console.error('Error downloading file:', error);
    }
  };

  const handleDeleteAttachment = async (attachmentId: number) => {
    try {
      await axios.delete(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/attachments/${attachmentId}`
      );

      // Remove attachment from list
      setAttachments((prevAttachments) =>
        prevAttachments.filter((attachment) => attachment.id !== attachmentId)
      );
      
      // Show success message
      enqueueSnackbar('File deleted successfully!', { variant: 'success' });
    } catch (error) {
      console.error('Error deleting attachment:', error);
      // Show error message
      enqueueSnackbar('Failed to delete file', { variant: 'error' });
    }
  };

  // Add this function to fetch attachments when component mounts
  const fetchAttachments = async () => {
    try {
      const response = await axios.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/${task.id}/attachments`
      );
      setAttachments(response.data);
    } catch (error) {
      console.error('Error fetching attachments:', error);
    }
  };

  // Add useEffect to fetch attachments when component mounts
  useEffect(() => {
    if (task?.id) {
      // Update attachments when task changes
      setAttachments(task?.attachments || []);
      // Still fetch to ensure we have the latest data
      fetchAttachments();
    }
  }, [task]);

  // Add this effect to fetch collaborators and manager data
  useEffect(() => {
    const fetchTaskUsers = async () => {
      if (!task) return;

      try {
        // Fetch collaborators
        if (task.collaboratorIds && task.collaboratorIds.length > 0) {
          const collaboratorPromises = task.collaboratorIds.map(id =>
            axios.get(
              `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/id`,
              { params: { Id: id } }
            )
          );
          const collaboratorResponses = await Promise.all(collaboratorPromises);
          setTaskCollaborators(collaboratorResponses.map(response => response.data));
        }

        // Fetch manager
        if (task.managerId) {
          const managerResponse = await axios.get(
            `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/id`,
            { params: { Id: task.managerId } }
          );
          setTaskManager(managerResponse.data);
        }
      } catch (error) {
        console.error('Failed to fetch task users:', error);
        enqueueSnackbar('Failed to fetch task users', { variant: 'error' });
      }
    };

    fetchTaskUsers();
  }, [task]);

  // Render functions
  const renderName = (
    <KanbanInputName
      placeholder="Task name"
      value={taskName}
      onChange={handleChangeTaskName}
      onKeyUp={handleUpdateTask}
    />
  );


  const renderDueDate = (
    <Stack direction="row" alignItems="center">
      <StyledLabel>Due date</StyledLabel>
      {endDate ? (
        <Button size="small" onClick={() => setShowDatePicker(true)}>
          {formatDate(endDate)}
        </Button>
      ) : (
        <Tooltip title="Add due date">
          <IconButton
            onClick={() => setShowDatePicker(true)}
            sx={{
              bgcolor: (theme) => alpha(theme.palette.grey[500], 0.08),
              border: (theme) => `dashed 1px ${theme.palette.divider}`,
            }}
          >
            <Iconify icon="mingcute:add-line" />
          </IconButton>
        </Tooltip>
      )}
      {showDatePicker && (
        <LocalizationProvider dateAdapter={AdapterDateFns}>
          <DatePicker
            open={true}
            value={endDate}
            onChange={handleDateChange}
            onClose={() => setShowDatePicker(false)}
          />
        </LocalizationProvider>
      )}
    </Stack>
  );

  const renderType = (
    <Stack direction="row" alignItems="center">
      <StyledLabel>Type</StyledLabel>
      <Stack direction="row" spacing={1}>
        <Button
          onClick={() => handleChangeType('BUG')}
          startIcon={<Iconify icon="solar:bug-bold" width={20} />}
          sx={{
            bgcolor: type === 'BUG' ? 'error.main' : 'transparent',
            color: type === 'BUG' ? 'white' : 'text.secondary',
            '&:hover': { bgcolor: type === 'BUG' ? 'error.dark' : 'action.hover' },
          }}
        >
          Bug
        </Button>
        <Button
          onClick={() => handleChangeType('FEATURE')}
          startIcon={<Iconify icon="solar:widget-bold" width={20} />}
          sx={{
            bgcolor: type === 'FEATURE' ? 'info.main' : 'transparent',
            color: type === 'FEATURE' ? 'white' : 'text.secondary',
            '&:hover': { bgcolor: type === 'FEATURE' ? 'info.dark' : 'action.hover' },
          }}
        >
          Feature
        </Button>
      </Stack>
    </Stack>
  );

  const renderHead = (
    <Stack
      direction="row"
      alignItems="center"
      justifyContent="space-between"
      sx={{ py: 2, pr: 1, pl: 2.5 }}
    >
      <Typography variant="h6">
        Task Details
      </Typography>

      <IconButton onClick={onCloseDetails}>
        <Iconify icon="mingcute:close-line" />
      </IconButton>
    </Stack>
  );

  const renderStatus = (
    <Stack direction="row" alignItems="center">
      <StyledLabel>Status</StyledLabel>
      <Stack direction="row" spacing={1}>
        <Button
          onClick={() => handleChangeStatus('TO DO')}
          startIcon={<Iconify icon="solar:clipboard-list-bold" width={20} />}
          sx={{
            bgcolor: status === 'TO DO' ? 'info.main' : 'transparent',
            color: status === 'TO DO' ? 'white' : 'text.secondary',
            '&:hover': { bgcolor: status === 'TO DO' ? 'info.dark' : 'action.hover' },
          }}
        >
          To Do
        </Button>
        <Button
          onClick={() => handleChangeStatus('IN PROGRESS')}
          startIcon={<Iconify icon="solar:clock-circle-bold" width={20} />}
          sx={{
            bgcolor: status === 'IN PROGRESS' ? 'warning.main' : 'transparent',
            color: status === 'IN PROGRESS' ? 'white' : 'text.secondary',
            '&:hover': { bgcolor: status === 'IN PROGRESS' ? 'warning.dark' : 'action.hover' },
          }}
        >
          In Progress
        </Button>
        <Button
          onClick={() => handleChangeStatus('DONE')}
          startIcon={<Iconify icon="solar:check-circle-bold" width={20} />}
          sx={{
            bgcolor: status === 'DONE' ? 'success.main' : 'transparent',
            color: status === 'DONE' ? 'white' : 'text.secondary',
            '&:hover': { bgcolor: status === 'DONE' ? 'success.dark' : 'action.hover' },
          }}
        >
          Done
        </Button>
      </Stack>
    </Stack>
  );

  const renderPriority = (
    <Stack direction="row" alignItems="center">
      <StyledLabel>Priority</StyledLabel>
      <Stack direction="row" spacing={1}>
        <Button
          onClick={() => handleChangePriority('LOW')}
          startIcon={<Iconify icon="solar:double-alt-arrow-down-bold" width={20} />}
          sx={{
            bgcolor: priority === 'LOW' ? 'success.main' : 'transparent',
            color: priority === 'LOW' ? 'white' : 'text.secondary',
            '&:hover': { bgcolor: priority === 'LOW' ? 'success.dark' : 'action.hover' },
          }}
        >
          Low
        </Button>
        <Button
          onClick={() => handleChangePriority('MEDIUM')}
          startIcon={<Iconify icon="solar:double-alt-arrow-right-bold" width={20} />}
          sx={{
            bgcolor: priority === 'MEDIUM' ? 'warning.main' : 'transparent',
            color: priority === 'MEDIUM' ? 'white' : 'text.secondary',
            '&:hover': { bgcolor: priority === 'MEDIUM' ? 'warning.dark' : 'action.hover' },
          }}
        >
          Medium
        </Button>
        <Button
          onClick={() => handleChangePriority('HIGH')}
          startIcon={<Iconify icon="solar:double-alt-arrow-up-bold" width={20} />}
          sx={{
            bgcolor: priority === 'HIGH' ? 'error.main' : 'transparent',
            color: priority === 'HIGH' ? 'white' : 'text.secondary',
            '&:hover': { bgcolor: priority === 'HIGH' ? 'error.dark' : 'action.hover' },
          }}
        >
          High
        </Button>
      </Stack>
    </Stack>
  );

  const renderDescription = (
    <Stack direction="row">
      <StyledLabel sx={{ mt: 2 }}>Description</StyledLabel>
      <Stack sx={{ width: '100%' }}>
        <div 
          dangerouslySetInnerHTML={{ __html: taskDescription }}
          style={{ 
            width: '100%',
            minHeight: '100px',
            border: '1px solid #ddd',
            padding: '8px',
            borderRadius: '4px',
            backgroundColor: 'white'
          }}
        />
      </Stack>
    </Stack>
  );

  const renderMark = (
    <Stack direction="row" alignItems="center">
      <StyledLabel>Mark</StyledLabel>
      <Stack direction="row" spacing={1}>
        <Tooltip title="1">
          <IconButton
            onClick={() => handleChangeMark(1)}
            sx={{
              bgcolor: taskMark === 1 ? 'success.main' : 'transparent',
              color: taskMark === 1 ? 'white' : 'text.secondary',
            }}
          >
            <Iconify icon="solar:star-bold" width={20} />
          </IconButton>
        </Tooltip>
        <Tooltip title="2">
          <IconButton
            onClick={() => handleChangeMark(2)}
            sx={{
              bgcolor: taskMark === 2 ? 'success.main' : 'transparent',
              color: taskMark === 2 ? 'white' : 'text.secondary',
            }}
          >
            <Iconify icon="solar:star-bold" width={20} />
          </IconButton>
        </Tooltip>
        <Tooltip title="3">
          <IconButton
            onClick={() => handleChangeMark(3)}
            sx={{
              bgcolor: taskMark === 3 ? 'success.main' : 'transparent',
              color: taskMark === 3 ? 'white' : 'text.secondary',
            }}
          >
            <Iconify icon="solar:star-bold" width={20} />
          </IconButton>
        </Tooltip>
        <Tooltip title="4">
          <IconButton
            onClick={() => handleChangeMark(4)}
            sx={{
              bgcolor: taskMark === 4 ? 'success.main' : 'transparent',
              color: taskMark === 4 ? 'white' : 'text.secondary',
            }}
          >
            <Iconify icon="solar:star-bold" width={20} />
          </IconButton>
        </Tooltip>
        <Tooltip title="5">
          <IconButton
            onClick={() => handleChangeMark(5)}
            sx={{
              bgcolor: taskMark === 5 ? 'success.main' : 'transparent',
              color: taskMark === 5 ? 'white' : 'text.secondary',
            }}
          >
            <Iconify icon="solar:star-bold" width={20} />
          </IconButton>
        </Tooltip>
      </Stack>
    </Stack>
  );

  const renderAttachments = (
    <Stack direction="row">
      <Typography variant="subtitle2" sx={{ color: 'text.secondary', mb: 0.5 }}>
        Attachments
      </Typography>
      <TaskDetailsAttachments
        attachments={task?.attachments}
        taskId={task?.id}
      />
    </Stack>
  );

  const renderCollaborators = (
    <Stack direction="row" alignItems="center">
      <StyledLabel>Collaborators</StyledLabel>
      <Stack direction="row" flexWrap="wrap" alignItems="center" spacing={1}>
        {taskCollaborators.map((collaborator) => (
          <Tooltip
            key={collaborator.id}
            title={`${collaborator.user.firstName} ${collaborator.user.lastName}`}
          >
            <Avatar
              alt={collaborator.user.lastName + " " + collaborator.user.firstName}
              sx={{ width: 40, height: 40 }}
            >
              {collaborator.user.firstName.charAt(0).toUpperCase() +
                collaborator.user.lastName.charAt(0).toUpperCase()}
            </Avatar>
          </Tooltip>
        ))}

        <Tooltip title="Add collaborator">
          <IconButton
            onClick={contacts.onTrue}
            sx={{
              bgcolor: (theme) => alpha(theme.palette.grey[500], 0.08),
              border: (theme) => `dashed 1px ${theme.palette.divider}`,
            }}
          >
            <Iconify icon="mingcute:add-line" />
          </IconButton>
        </Tooltip>

        <KanbanContactsDialog
          taskId={task.id}
          open={contacts.value}
          onClose={contacts.onFalse}
          collaborators={taskCollaborators}
          projectId={task.projectId}
          onUpdateCollaborators={(newCollaborators) => {
            setTaskCollaborators(newCollaborators);
            // Update the task with new collaborator IDs
            onUpdateTask({
              ...task,
              collaboratorIds: newCollaborators.map(c => c.id)
            });
            contacts.onFalse();
          }}
        />
      </Stack>
    </Stack>
  );

  const renderManager = (
    <Stack direction="row" alignItems="center">
      <StyledLabel>Manager</StyledLabel>
      {taskManager ? (
        <Tooltip
          title={`${taskManager.user.firstName} ${taskManager.user.lastName}`}
        >
          <Avatar
            alt={taskManager.user.lastName + " " + taskManager.user.firstName}
            sx={{ width: 40, height: 40 }}
          >
            {taskManager.user.firstName.charAt(0).toUpperCase() +
              taskManager.user.lastName.charAt(0).toUpperCase()}
          </Avatar>
        </Tooltip>
      ) : (
        <Typography variant="body2" color="text.secondary">
          No manager assigned
        </Typography>
      )}
    </Stack>
  );

  return (
    <Drawer
      open={openDetails}
      onClose={onCloseDetails}
      anchor="right"
      slotProps={{
        backdrop: { invisible: true },
      }}
      PaperProps={{
        sx: {
          width: {
            xs: 1,
            sm: 480,
            md: 600,
          },
        },
      }}
    >
      {renderHead}

      <Divider />
      <DialogContent sx={{ overflowY: 'auto' }} dividers>
        <Grid container spacing={3}>
          <Grid item xs={12}>
            {renderName}
            <Scrollbar
              sx={{
                height: 'calc(100vh - 200px)',
                '& .simplebar-content': {
                  height: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                },
              }}
            >
              <Stack
                spacing={3}
                sx={{
                  pt: 3,
                  pb: 5,
                  px: 2.5,
                  width: '100%',
                }}
              >
                {renderDueDate}
                {renderType}
                {renderStatus}
                {renderPriority}
                {renderDescription}
                {renderMark}
                {renderManager}
                {renderCollaborators}
                <TabContext value={tabValue}>
                  <Box sx={{ borderBottom: 1, borderColor: 'divider', width: '100%' }}>
                    <Tabs 
                      value={tabValue} 
                      onChange={handleTabChange}
                      variant="fullWidth"
                    >
                      <Tab 
                        label="Attachments" 
                        value="attachments" 
                        icon={<AttachFileIcon />} 
                      />
                    </Tabs>
                  </Box>
                  <TabPanel value="attachments" sx={{ p: 0, mt: 2 }}>
                    {renderAttachments}
                  </TabPanel>
                </TabContext>
              </Stack>
            </Scrollbar>
          </Grid>
        </Grid>
      </DialogContent>
    </Drawer>
  );
}
