'use client';

import React, { useEffect, useRef, useState } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { fetchVolunteerShifts, updateVolunteerSlot } from '@/services/volunteerShift.service';
import { fetchVolunteerSlots, exportSlotsToCSV } from '@/services/volunteerSlot.service';
import ClearIcon from '@mui/icons-material/Clear';
import DoneIcon from '@mui/icons-material/Done';
import EditIcon from '@mui/icons-material/Edit';
import FileDownloadIcon from '@mui/icons-material/FileDownload';
import {
  Avatar,
  Box,
  Button,
  FormControl,
  FormHelperText,
  IconButton,
  InputLabel,
  OutlinedInput,
  Paper,
  Stack,
  Tab,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tabs,
  Typography,
  useTheme,
} from '@mui/material';
import { AppLoader } from '@/components/core/app-loader';
import { enqueueSnackbar } from 'notistack';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';

dayjs.extend(utc);

import { IShift } from '@/types/shift.type';
import { ISlot } from '@/types/slot.type';

import AddDateSlotModal from './addDateSlotModal';
import AddSlotModal from './addSlotModal';
import EditShiftModal from './EditShiftModal';

const slotData = [
  {
    date: '01/14/2025',
    day: 'Tuesday',
    slots: [
      {
        time: '12:00pm-2:00pm',
        title: 'Volunteer',
        status: 'Full',
        filledSlots: 2,
        maxSlots: 2,
        participants: [
          { name: 'Mark Wane', phone: '125414141', initials: 'MW' },
          { name: 'Mark Henry', phone: '1011045585', initials: 'MH' },
        ],
      },
      {
        time: '2:00pm-4:00pm',
        title: 'Volunteer',
        status: 'Open',
        filledSlots: 0,
        maxSlots: 2,
        participants: [],
      },
    ],
  },
];

function a11yProps(index: number) {
  return {
    id: `simple-tab-${index}`,
    'aria-controls': `simple-tabpanel-${index}`,
  };
}

// Convert time string from UTC to local time
// Input: time string like "5:48PM-5:50PM" and date string like "11/03/2025"
// Output: time string in local time like "5:48PM-5:50PM"
const convertTimeToLocal = (timeString: string, dateString: string): string => {
  if (!timeString || !dateString) return timeString;
  
  try {
    // Parse the time string (format: "5:48PM-5:50PM" or "11:43AM-11:45AM")
    const [startTimeStr, endTimeStr] = timeString.split('-').map(t => t.trim());
    
    if (!startTimeStr || !endTimeStr) return timeString;
    
    // Parse date (format: "11/03/2025" - MM/DD/YYYY)
    const dateParts = dateString.split('/');
    if (dateParts.length !== 3) return timeString;
    
    const month = parseInt(dateParts[0], 10) - 1; // month is 0-indexed
    const day = parseInt(dateParts[1], 10);
    const year = parseInt(dateParts[2], 10);
    
    // Helper to parse time string (e.g., "5:48PM" or "11:43AM")
    const parseTime = (timeStr: string): { hour: number; minute: number } => {
      const isPM = timeStr.toUpperCase().includes('PM');
      const timePart = timeStr.replace(/[AP]M/i, '').trim();
      const [hours, minutes] = timePart.split(':').map(Number);
      
      let hour24 = hours;
      if (isPM && hours !== 12) {
        hour24 = hours + 12;
      } else if (!isPM && hours === 12) {
        hour24 = 0;
      }
      
      return { hour: hour24, minute: minutes || 0 };
    };
    
    // Parse start and end times
    const startTime = parseTime(startTimeStr);
    const endTime = parseTime(endTimeStr);
    
    // Create UTC datetime objects using dayjs.utc() with proper UTC date construction
    const startDateTimeUTC = dayjs.utc(`${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(startTime.hour).padStart(2, '0')}:${String(startTime.minute).padStart(2, '0')}:00`);
    const endDateTimeUTC = dayjs.utc(`${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(endTime.hour).padStart(2, '0')}:${String(endTime.minute).padStart(2, '0')}:00`);
    
    // Convert to local time
    const startDateTimeLocal = startDateTimeUTC.local();
    const endDateTimeLocal = endDateTimeUTC.local();
    
    // Format back to "HH:MMAM/PM-HH:MMAM/PM" format
    const formatTime = (dt: dayjs.Dayjs): string => {
      const hour12 = dt.hour() % 12 || 12;
      const minute = dt.minute();
      const ampm = dt.hour() >= 12 ? 'PM' : 'AM';
      return `${hour12}:${minute.toString().padStart(2, '0')}${ampm}`;
    };
    
    return `${formatTime(startDateTimeLocal)}-${formatTime(endDateTimeLocal)}`;
  } catch (error) {
    console.error('Error converting time to local:', error);
    return timeString; // Return original if conversion fails
  }
};

const Slots = () => {
  const theme = useTheme();
  const router = useRouter();
  const searchParams = useSearchParams();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isSlotModalOpen, setIsSlotModalOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isShiftLoading, setIsShiftLoading] = useState(false);
  const [shifts, setShifts] = useState<IShift[]>([]);
  const [slots, setSlots] = useState<ISlot[]>([]);
  const [value, setValue] = React.useState('shifts');
  const [isEdit, setIsEdit] = useState<{
    createdAt: string;
    isDeleted: boolean;
    numberOfSlots: number;
    slotName: string;
    updatedAt: string;
    _id: string;
    slotNameError: string | null;
    numberOfSlotsError: string | null;
    loading?: boolean;
  } | null>(null);
  const [isExporting, setIsExporting] = useState(false);
  const [editingShift, setEditingShift] = useState<any>(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);

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

  const pathname = usePathname();

  useEffect(() => {
    const param = searchParams.get('modal');
    if (param) {
      setIsModalOpen(true);
    } else {
      setIsModalOpen(false);
    }
  }, [searchParams]);

  useEffect(() => {
    const param = searchParams.get('slot_modal');
    if (param) {
      setIsSlotModalOpen(true);
    } else {
      fetchSlots();
      setIsSlotModalOpen(false);
    }
  }, [searchParams]);

  const openModal = () => {
    router.replace(`?modal=1`);
  };

  const closeModal = () => {
    setIsModalOpen(false);
    const currentParams = new URLSearchParams(searchParams);
    currentParams.delete('modal');
    const newUrl = `${pathname}${currentParams.toString() ? `?${currentParams}` : ''}`;
    router.replace(newUrl);
  };

  const closeSlotModal = () => {
    setIsSlotModalOpen(false);
    const currentParams = new URLSearchParams(searchParams);
    currentParams.delete('slot_modal');
    const newUrl = `${pathname}${currentParams.toString() ? `?${currentParams}` : ''}`;
    router.replace(newUrl);
  };

  const fetchSlots = async () => {
    try {
      setIsLoading(true);
      const response = await fetchVolunteerSlots();
      setSlots(response?.data?.data);
      setIsLoading(false);
    } catch (error) {
      console.error('Error in creating volunteer slot:', error);
      enqueueSnackbar('Error in creating volunteer slot', { variant: 'error' });
      setIsLoading(false);
    }
  };

  const fetchShifts = async () => {
    try {
      setIsShiftLoading(true);
      const response = await fetchVolunteerShifts();
      setShifts(response?.data?.data);
      setIsShiftLoading(false);
    } catch (error) {
      console.error('Error in creating volunteer slot:', error);
      enqueueSnackbar('Error in fetching volunteer shifts', { variant: 'error' });
      setIsShiftLoading(false);
    }
  };

  useEffect(() => {
    fetchSlots();
    fetchShifts();
  }, []);

  const handleUpdateSlot = async () => {
    if (isEdit) {
      setIsEdit((prev) => (prev ? { ...prev, loading: true } : null));
      try {
        const response = await updateVolunteerSlot(isEdit?._id, {
          numberOfSlots: isEdit.numberOfSlots,
          slotName: isEdit.slotName,
        });
        enqueueSnackbar('Volunteer slot updated successfully', { variant: 'success' });
        setIsEdit(null);
        fetchSlots();
      } catch (error) {
        console.error('Error in creating volunteer slot:', error);
        enqueueSnackbar('Error in creating volunteer slot', { variant: 'error' });
        setIsEdit((prev) => (prev ? { ...prev, loading: false } : null));
      }
    }
  };

  const handleExportSlots = async () => {
    try {
      setIsExporting(true);
      await exportSlotsToCSV();
      enqueueSnackbar('Slots exported successfully', { variant: 'success' });
    } catch (error) {
      console.error('Error exporting slots:', error);
      enqueueSnackbar('Error exporting slots', { variant: 'error' });
    } finally {
      setIsExporting(false);
    }
  };

  // Handle editing a specific shift
  const handleEditShift = (shift: any, dayData: any) => {
    console.log('Editing shift:', shift, 'from day:', dayData);
    
    // Check if this is a new shift or existing shift
    if (!shift._id && !shift.id) {
      // This is a new shift - don't generate a fake ID, let the backend handle it
      enqueueSnackbar('Cannot edit shift without a valid ID. Please create a new shift instead.', { variant: 'warning' });
      return;
    }
    
    // Create a proper shift object for editing
    const shiftData = {
      ...shift,
      date: dayData.date,
      day: dayData.day,
      _id: shift._id || shift.id, // Use existing ID only
      slotId: shift.slotId || slots[0]?._id || '', // Default to first slot if no slotId
    };
    
    console.log('Shift data being set for editing:', shiftData);
    setEditingShift(shiftData);
    setIsEditModalOpen(true);
  };

  // Handle editing an entire day's shifts
  const handleEditDay = (dayData: any) => {
    console.log('Editing day:', dayData);
    // For day editing, we'll edit the first shift of the day
    if (dayData.slots && dayData.slots.length > 0) {
      handleEditShift(dayData.slots[0], dayData);
    } else {
      enqueueSnackbar('No shifts found for this day', { variant: 'warning' });
    }
  };

  // Close edit modal
  const closeEditModal = () => {
    setIsEditModalOpen(false);
    setEditingShift(null);
  };

  return (
    <Box sx={{ bgcolor: 'background.default', minHeight: '100vh', p: 3 }}>
      {/* Modern Header Section */}
      <Paper
        elevation={0}
        sx={{
          p: 3,
          mb: 3,
          borderRadius: 4,
          background: '#FFDD31',
          color: '#0B0504',
        }}
      >
        <Stack direction="row" justifyContent="space-between" alignItems="center">
          <Box>
            <Typography variant="h4" fontWeight={700} gutterBottom>
              Volunteer Slots Management
            </Typography>
            <Typography variant="body1" sx={{ opacity: 0.9 }}>
              Manage volunteer time slots and shift assignments
            </Typography>
          </Box>
          <Stack direction="row" spacing={2}>
            <Button
              variant="contained"
              onClick={() => openModal()}
              sx={{
                bgcolor: 'rgba(11, 5, 4, 0.8)',
                color: '#FFDD31',
                borderRadius: 3,
                px: 3,
                py: 1.5,
                fontWeight: 600,
                border: '1px solid rgba(11, 5, 4, 0.9)',
                '&:hover': {
                  bgcolor: 'rgba(11, 5, 4, 0.9)',
                  transform: 'translateY(-2px)',
                },
                transition: 'all 0.3s ease',
              }}
            >
              Add Date Slot
            </Button>
            <Button
              variant="contained"
              onClick={handleExportSlots}
              disabled={isExporting}
              startIcon={isExporting ? <AppLoader size="xs" inline color="#FFDD31" /> : <FileDownloadIcon />}
              sx={{
                bgcolor: 'rgba(11, 5, 4, 0.8)',
                color: '#FFDD31',
                borderRadius: 3,
                px: 3,
                py: 1.5,
                fontWeight: 600,
                border: '1px solid rgba(11, 5, 4, 0.9)',
                '&:hover': {
                  bgcolor: 'rgba(11, 5, 4, 0.9)',
                  transform: 'translateY(-2px)',
                },
                '&:disabled': {
                  bgcolor: 'rgba(11, 5, 4, 0.4)',
                  color: 'rgba(255, 221, 49, 0.5)',
                  border: '1px solid rgba(11, 5, 4, 0.4)',
                },
                transition: 'all 0.3s ease',
              }}
            >
              {isExporting ? 'Exporting...' : 'Export CSV'}
            </Button>
          </Stack>
        </Stack>
      </Paper>

      {/* Modern Tabs */}
      <Paper
        elevation={0}
        sx={{
          mb: 3,
          borderRadius: 3,
          border: theme.palette.mode === 'dark' ? '1px solid #4a5568' : '1px solid #e2e8f0',
          overflow: 'hidden',
        }}
      >
        <Tabs
          value={value}
          onChange={handleChange}
          sx={{
            minHeight: 48,
            '& .MuiTabs-indicator': {
              display: 'none',
            },
            '& .MuiTab-root': {
              textTransform: 'none',
              minHeight: 48,
              fontWeight: 600,
              color: 'text.secondary',
              paddingLeft: 2,
              '&.Mui-selected': {
                color: 'white',
                bgcolor: theme.palette.mode === 'dark' ? '#4a5568' : '#667eea',
              },
            },
          }}
        >
          <Tab label="Shifts Management" {...a11yProps(0)} value={'shifts'} />
          <Tab label="Slots Configuration" {...a11yProps(1)} value={'slots'} />
        </Tabs>
      </Paper>

      {/* Shifts Tab */}
      <div
        role="tabpanel"
        hidden={value !== 'shifts'}
        id={`simple-tabpanel-shifts`}
        aria-labelledby={`simple-tab-shifts`}
      >
        <Paper
          elevation={0}
          sx={{
            borderRadius: 4,
             background: theme.palette.mode === 'dark' 
                ? 'linear-gradient(145deg, #1a202c 0%, #2d3748 100%)' 
                : 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
              border: theme.palette.mode === 'dark' ? '1px solid #4a5568' : '1px solid rgba(255, 255, 255, 0.2)',
            boxShadow: '0 8px 32px rgba(0, 0, 0, 0.08)',
            overflow: 'hidden',
            minHeight: '25rem',
            position: 'relative',
          }}
        >
          {isShiftLoading && <AppLoader fill size="lg" label="Loading shifts..." />}
          <TableContainer sx={{ maxHeight: '500px', overflow: 'auto' }}>
            <Table>
              <TableHead>
                <TableRow
                  sx={{
                    '& .MuiTableCell-head': {
                      backgroundColor: theme.palette.mode === 'dark' ? '#2d3748' : '#f8fafc',
                      fontWeight: 700,
                      color: 'text.primary',
                      borderBottom: theme.palette.mode === 'dark' ? '2px solid #4a5568' : '2px solid #e5e7eb',
                      py: 2,
                    }
                  }}
                >
                  <TableCell sx={{ width: '150px' }}>Date</TableCell>
                  <TableCell sx={{ width: '130px' }}>Time</TableCell>
                  <TableCell>Available Slots & Participants</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {shifts.map((dayData, index) => (
                  <React.Fragment key={index}>
                    <TableRow
                      data-date-row
                      data-date={dayData.date}
                      sx={{
                        backgroundColor: theme.palette.mode === 'dark' ? '#4a5568' : '#667eea',
                        '&:hover': {
                          backgroundColor: theme.palette.mode === 'dark' ? '#2d3748' : '#5a6fd8',
                        },
                      }}
                    >
                      <TableCell
                        rowSpan={dayData.slots.length + 1}
                        sx={{
                          verticalAlign: 'top',
                          p: '16px 16px 0px 16px',
                          border: '1px solid rgba(255, 255, 255, 0.2)',
                          position: 'relative',
                          color: 'white',
                          '& button': {
                            opacity: 0,
                            visibility: 'hidden',
                            transition: '0.2s all',
                            position: 'absolute',
                            top: 8,
                            right: 8,
                            color: 'white',
                          },
                          '&:hover': {
                            '& button': {
                              opacity: 1,
                              visibility: 'visible',
                            },
                          },
                        }}
                      >
                        <div style={{ position: 'sticky', top: '16px' }}>
                          <Typography variant="body1" sx={{ fontWeight: 700, color: 'white' }}>
                            {dayData.date}
                          </Typography>
                          <Typography variant="body2" sx={{ color: 'rgba(255, 255, 255, 0.8)' }}>
                            {dayData.day}
                          </Typography>
                        </div>
                        <IconButton onClick={() => handleEditDay(dayData)}>
                          <EditIcon />
                        </IconButton>
                      </TableCell>
                    </TableRow>
                    {dayData.slots.map((slot, slotIndex) => (
                      <TableRow 
                        key={slotIndex} 
                        sx={{ 
                          backgroundColor: theme.palette.mode === 'dark' ? '#2d3748' : '#f8fafc',
                          '&:hover': {
                            backgroundColor: theme.palette.mode === 'dark' ? '#1a202c' : '#f1f5f9',
                            transform: 'scale(1.001)',
                            transition: 'all 0.2s ease-in-out',
                          },
                        }}
                      >
                        <TableCell
                          sx={{
                            verticalAlign: 'top',
                            border: theme.palette.mode === 'dark' ? '1px solid #4a5568' : '1px solid #e5e7eb',
                            position: 'relative',
                            '& button': {
                              opacity: 0,
                              visibility: 'hidden',
                              transition: '0.2s all',
                              position: 'absolute',
                              top: 8,
                              right: 8,
                              color: theme.palette.mode === 'dark' ? '#4a5568' : '#667eea',
                            },
                            '&:hover': {
                              '& button': {
                                opacity: 1,
                                visibility: 'visible',
                              },
                            },
                          }}
                        >
                          <div style={{ position: 'sticky', top: '16px' }}>
                            <Typography variant="body2" fontWeight={600} color="text.primary">
                              {convertTimeToLocal(slot.time, dayData.date)}
                            </Typography>
                          </div>
                          <IconButton onClick={() => handleEditShift(slot, dayData)}>
                            <EditIcon />
                          </IconButton>
                        </TableCell>
                        <TableCell sx={{ border: '1px solid #e5e7eb' }}>
                          <Stack direction={'row'} justifyContent={'space-between'}>
                            <Stack>
                              <Typography variant="subtitle1" fontWeight={600} color="text.primary" gutterBottom>
                                {slot.title}
                              </Typography>
                              <Typography
                                variant="caption"
                                sx={{
                                  display: 'block',
                                  marginBottom: '8px',
                                  color: slot.filledSlots === slot.maxSlots ? '#dc2626' : '#059669',
                                  fontWeight: 500,
                                }}
                              >
                                {`${slot.filledSlots} of ${slot.maxSlots} slots filled`}
                              </Typography>
                            </Stack>
                          </Stack>
                          <Stack direction={'row'} justifyContent={'flex-end'}>
                            <Stack>
                              {slot.participants.length > 0 &&
                                slot.participants.map((participant, participantIndex) => (
                                  <Box
                                    key={participantIndex}
                                    sx={{ display: 'flex', alignItems: 'center', gap: '8px', mb: 1 }}
                                  >
                                    <Avatar sx={{ 
                                      bgcolor: theme.palette.mode === 'dark' ? '#4a5568' : '#667eea', 
                                      width: 36, 
                                      height: 36,
                                      fontSize: '0.875rem',
                                      fontWeight: 600,
                                    }}>
                                      {participant.initials}
                                    </Avatar>
                                    <Box>
                                      <Typography variant="body2" fontWeight={500} color="text.primary">
                                        {participant.name}
                                      </Typography>
                                      <Typography variant="caption" color="text.secondary">
                                        {participant.phone}
                                      </Typography>
                                    </Box>
                                  </Box>
                                ))}
                            </Stack>
                          </Stack>
                        </TableCell>
                      </TableRow>
                    ))}
                  </React.Fragment>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </Paper>
      </div>

      {/* Slots Tab */}
      <div
        role="tabpanel"
        hidden={value !== 'slots'}
        id={`simple-tabpanel-slots`}
        aria-labelledby={`simple-tab-slots`}
      >
        <Paper
          elevation={0}
          sx={{
            borderRadius: 4,
            background: theme.palette.mode === 'dark' 
              ? 'linear-gradient(145deg, #2d3748 0%, #1a202c 100%)' 
              : 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
            border: theme.palette.mode === 'dark' ? '1px solid #4a5568' : '1px solid rgba(255, 255, 255, 0.2)',
            boxShadow: '0 8px 32px rgba(0, 0, 0, 0.08)',
            overflow: 'hidden',
            position: 'relative',
            minHeight: '25rem',
          }}
        >
          {isLoading && <AppLoader fill size="lg" label="Loading slots..." />}
          <TableContainer sx={{ maxHeight: '500px', overflow: 'auto' }}>
            <Table stickyHeader>
              <TableHead>
                <TableRow
                  sx={{
                    '& .MuiTableCell-head': {
                      backgroundColor: theme.palette.mode === 'dark' ? '#2d3748' : '#f8fafc',
                      fontWeight: 700,
                      color: 'text.primary',
                      borderBottom: theme.palette.mode === 'dark' ? '2px solid #4a5568' : '2px solid #e5e7eb',
                      py: 2,
                    }
                  }}
                >
                  <TableCell>Slot Name</TableCell>
                  <TableCell>Number Of Slots</TableCell>
                  <TableCell align="center" sx={{ width: '100px' }}>Actions</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {slots.map((slot, index) => {
                  const isEditable = isEdit && isEdit._id === slot._id;
                  return (
                    <React.Fragment key={index}>
                      <TableRow
                        sx={{
                          '&:hover': {
                            backgroundColor: theme.palette.mode === 'dark' ? '#2d3748' : '#f8fafc',
                            transform: 'scale(1.001)',
                            transition: 'all 0.2s ease-in-out',
                          },
                          '& .MuiTableCell-root': {
                            borderBottom: theme.palette.mode === 'dark' ? '1px solid #4a5568' : '1px solid #f1f5f9',
                            py: 2,
                          }
                        }}
                      >
                        <TableCell sx={{ verticalAlign: 'top', position: 'relative' }}>
                          {isEditable ? (
                            <FormControl fullWidth size="small">
                              <InputLabel>Slot Name</InputLabel>
                              <OutlinedInput
                                label="Slot Name"
                                value={isEdit.slotName}
                                onChange={(e) =>
                                  setIsEdit((prev) =>
                                    prev
                                      ? {
                                          ...prev,
                                          slotName: e.target.value,
                                          slotNameError:
                                            e.target.value.length === 0 ? 'Slot name is required' : null,
                                        }
                                      : null
                                  )
                                }
                              />
                              {isEdit.slotNameError && (
                                <FormHelperText error>{isEdit.slotNameError}</FormHelperText>
                              )}
                            </FormControl>
                          ) : (
                            slot.slotName
                          )}
                        </TableCell>
                        <TableCell sx={{ verticalAlign: 'top', position: 'relative' }}>
                          {isEditable ? (
                            <FormControl fullWidth size="small">
                              <InputLabel>Number Of Slots</InputLabel>
                              <OutlinedInput
                                label="Number Of Slots"
                                value={isEdit.numberOfSlots}
                                type="number"
                                onChange={(e) =>
                                  setIsEdit((prev) =>
                                    prev
                                      ? {
                                          ...prev,
                                          numberOfSlots: parseInt(e.target.value),
                                          numberOfSlotsError:
                                            parseInt(e.target.value) === 0 || Number.isNaN(parseInt(e.target.value))
                                              ? 'Number of slots is required'
                                              : null,
                                        }
                                      : null
                                  )
                                }
                              />
                              {isEdit.numberOfSlotsError && (
                                <FormHelperText error>{isEdit.numberOfSlotsError}</FormHelperText>
                              )}
                            </FormControl>
                          ) : (
                            slot.numberOfSlots
                          )}
                        </TableCell>
                        <TableCell align="center" sx={{ verticalAlign: 'middle', position: 'relative' }}>
                          <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 10 }}>
                            {isEditable ? (
                              <>
                                <IconButton
                                  sx={{ p: 0 }}
                                  onClick={() => {
                                    setIsEdit(null);
                                  }}
                                >
                                  <ClearIcon fontSize="small" color="error" />
                                </IconButton>

                                {isEdit?.loading ? (
                                  <AppLoader size="xs" inline />
                                ) : (
                                  <IconButton
                                    sx={{
                                      p: 0.5,
                                      color: '#059669',
                                      '&:hover': {
                                        backgroundColor: '#f0fdf4',
                                        transform: 'scale(1.1)',
                                      },
                                      '&:disabled': {
                                        color: '#9ca3af',
                                        opacity: 0.6
                                      },
                                      transition: 'all 0.2s ease-in-out',
                                    }}
                                    onClick={() => {
                                      handleUpdateSlot();
                                    }}
                                    disabled={isEdit.numberOfSlotsError || isEdit.slotNameError ? true : false}
                                  >
                                    <DoneIcon fontSize="small" />
                                  </IconButton>
                                )}
                              </>
                            ) : (
                              <IconButton
                                sx={{ 
                                  p: 0.5,
                                  color: theme.palette.mode === 'dark' ? '#4a5568' : '#667eea',
                                  '&:hover': {
                                    backgroundColor: theme.palette.mode === 'dark' ? '#2d3748' : '#f0f4ff',
                                    transform: 'scale(1.1)',
                                  },
                                  transition: 'all 0.2s ease-in-out',
                                }}
                                onClick={() => {
                                  setIsEdit({ ...slot, numberOfSlotsError: null, slotNameError: null });
                                }}
                              >
                                <EditIcon fontSize="small" />
                              </IconButton>
                            )}
                          </div>
                        </TableCell>
                      </TableRow>
                    </React.Fragment>
                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>
        </Paper>
      </div>

      <AddDateSlotModal open={isModalOpen} handleClose={closeModal} slots={slots} refetch={() => fetchShifts()} />
      <AddSlotModal open={isSlotModalOpen} handleClose={closeSlotModal} />
      <EditShiftModal 
        open={isEditModalOpen} 
        handleClose={closeEditModal} 
        slots={slots} 
        editingShift={editingShift}
        refetch={() => fetchShifts()} 
      />
    </Box>
  );
};

export default Slots;