import { useState, useEffect, useRef } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuSeparator,
  ContextMenuTrigger,
} from "@/components/ui/context-menu";
import {
  HoverCard,
  HoverCardContent,
  HoverCardTrigger,
} from "@/components/ui/hover-card";
import { Search, Filter, SortAsc, Calendar, ChevronLeft, ChevronRight, Edit, Timer, CheckCircle, Play, Clock, Trash2, Tag } from 'lucide-react';
import { Task, Label } from '@shared/schema';
import TaskCard from './TaskCard';
import { useQuery } from '@tanstack/react-query';
import TimeCompletionModal from './TimeCompletionModal';
import { addDays, format, isSameDay, startOfToday, startOfDay, isWithinInterval } from 'date-fns';
import { useTranslation } from 'react-i18next';
import { useDateLocale } from '../hooks/use-date-locale';

interface TasksWithCalendarProps {
  tasks: Task[];
  onTaskUpdate?: (taskId: string, updates: Partial<Task>) => void;
  onTaskEdit?: (task: Task) => void;
  onTaskDelete?: (taskId: string) => void;
  onStartTimer?: (taskId: string) => void;
  onStopTimer?: (taskId: string) => void;
}

type SortOption = 'dueDate' | 'priority' | 'title' | 'status';
type FilterOption = 'all' | 'open' | 'todo' | 'inProgress' | 'done' | 'overdue' | 'planned' | 'unplanned';

export default function TasksWithCalendar({ tasks, onTaskUpdate, onTaskEdit, onTaskDelete, onStartTimer, onStopTimer }: TasksWithCalendarProps) {
  const { t } = useTranslation();
  const dateLocale = useDateLocale();
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState<SortOption>('dueDate');
  const [filterBy, setFilterBy] = useState<FilterOption>('open');
  const [filterByLabel, setFilterByLabel] = useState<string>('all');
  const [calendarStartDate, setCalendarStartDate] = useState(startOfToday());
  const [draggedTask, setDraggedTask] = useState<string | null>(null);
  const [hoveredDate, setHoveredDate] = useState<Date | null>(null);
  const [visibleDays, setVisibleDays] = useState(7);
  const [completionModal, setCompletionModal] = useState<{ isOpen: boolean; task: Task | null }>({
    isOpen: false,
    task: null
  });

  // Fetch labels to get label colors
  const { data: labels = [] } = useQuery<Label[]>({
    queryKey: ['/api/labels'],
    staleTime: 5 * 60 * 1000, // 5 minutes cache
    refetchOnWindowFocus: false,
  });

  // Calculate responsive visible days based on available container width
  const containerRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const calculateVisibleDays = () => {
      // Use actual container width (accounts for sidebar) instead of window.innerWidth
      const containerWidth = containerRef.current?.offsetWidth ?? window.innerWidth;
      // Subtract padding (approximately 32px total)
      const availableWidth = containerWidth - 32;
      // Minimum width per day card (including gaps): ~120px
      const minDayWidth = 120;
      const maxDays = Math.floor(availableWidth / minDayWidth);

      // Clamp between 2 and 7 days
      const calculated = Math.max(2, Math.min(7, maxDays));
      setVisibleDays(calculated);
    };

    calculateVisibleDays();
    window.addEventListener('resize', calculateVisibleDays);

    return () => window.removeEventListener('resize', calculateVisibleDays);
  }, []);

  // Get dynamic number of days starting from calendar start date
  const dates = Array.from({ length: visibleDays }, (_, i) => addDays(calendarStartDate, i));

  const isOverdue = (task: Task) => {
    if (!task.dueDate) return false;
    return task.dueDate < new Date() && task.status !== 'done';
  };

  const filteredAndSortedTasks = tasks
    .filter(task => {
      // Search filter
      const matchesSearch = task.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        task.description?.toLowerCase().includes(searchQuery.toLowerCase());

      if (!matchesSearch) return false;

      // Label filter
      if (filterByLabel !== 'all') {
        if (task.labelId !== filterByLabel) return false;
      }

      // Status filter
      switch (filterBy) {
        case 'overdue':
          return isOverdue(task);
        case 'planned':
          return !!task.dueDate || !!task.startDate;
        case 'unplanned':
          return !task.dueDate && !task.startDate;
        case 'all':
          return true;
        case 'open':
          return task.status !== 'done';
        default:
          return task.status === filterBy;
      }
    })
    .sort((a, b) => {
      switch (sortBy) {
        case 'dueDate':
          if (!a.dueDate && !b.dueDate) return 0;
          if (!a.dueDate) return 1;
          if (!b.dueDate) return -1;
          return a.dueDate.getTime() - b.dueDate.getTime();

        case 'priority':
          const priorityOrder = { high: 3, medium: 2, low: 1 };
          return priorityOrder[b.priority as keyof typeof priorityOrder] - priorityOrder[a.priority as keyof typeof priorityOrder];

        case 'title':
          return a.title.localeCompare(b.title);

        case 'status':
          const statusOrder = { todo: 1, inProgress: 2, done: 3 };
          return statusOrder[a.status as keyof typeof statusOrder] - statusOrder[b.status as keyof typeof statusOrder];

        default:
          return 0;
      }
    });

  // Tasks that are NOT on the calendar (no due date OR not in visible dates)
  const unscheduledTasks = filteredAndSortedTasks.filter(task => {
    if (!task.dueDate) return true;
    const isVisible = dates.some(date => isSameDay(date, task.dueDate!));
    return !isVisible;
  });

  const getTasksForDate = (date: Date) => {
    return filteredAndSortedTasks.filter(task => {
      // Handle multi-day tasks
      if (task.startDate && task.dueDate) {
        const start = startOfDay(new Date(task.startDate));
        const end = startOfDay(new Date(task.dueDate));
        const current = startOfDay(date);
        return current >= start && current <= end;
      }

      // Handle single date tasks (dueDate or startDate)
      if (task.dueDate) {
        return isSameDay(new Date(task.dueDate), date);
      }
      if (task.startDate) {
        return isSameDay(new Date(task.startDate), date);
      }

      return false;
    });
  };

  const getFilterCount = (filter: FilterOption) => {
    switch (filter) {
      case 'overdue':
        return tasks.filter(isOverdue).length;
      case 'planned':
        return tasks.filter(t => !!t.dueDate || !!t.startDate).length;
      case 'unplanned':
        return tasks.filter(t => !t.dueDate && !t.startDate).length;
      case 'all':
        return tasks.length;
      case 'open':
        return tasks.filter(t => t.status !== 'done').length;
      default:
        return tasks.filter(task => task.status === filter).length;
    }
  };

  const handleDragStart = (taskId: string, e: React.DragEvent) => {
    setDraggedTask(taskId);
    e.dataTransfer.effectAllowed = 'move';
    console.log('Drag started for task:', taskId);
  };

  const handleDragEnd = () => {
    setDraggedTask(null);
  };

  const handleDrop = (date: Date, e: React.DragEvent) => {
    e.preventDefault();
    if (draggedTask) {
      onTaskUpdate?.(draggedTask, { dueDate: date });
      console.log(`Task ${draggedTask} moved to`, date.toLocaleDateString());
      setDraggedTask(null);
    }
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
  };

  const handleDragEnter = (date: Date) => {
    if (draggedTask) {
      setHoveredDate(date);
    }
  };

  const handleDragLeave = (e: React.DragEvent) => {
    // Only clear hover if we're leaving the calendar entirely
    const rect = e.currentTarget.getBoundingClientRect();
    const x = e.clientX;
    const y = e.clientY;

    if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
      setHoveredDate(null);
    }
  };

  const handleMouseMove = (e: React.MouseEvent, date: Date) => {
    if (draggedTask) {
      setHoveredDate(date);
    }
  };

  const navigateCalendar = (direction: 'prev' | 'next') => {
    const newDate = addDays(calendarStartDate, direction === 'next' ? visibleDays : -visibleDays);
    setCalendarStartDate(newDate);
    console.log(`Navigating calendar to ${newDate.toLocaleDateString()}, showing ${visibleDays} days`);
  };

  const handleTaskComplete = (task: Task) => {
    setCompletionModal({ isOpen: true, task });
  };

  const handleTimeLogged = (timeSpent: number) => {
    if (completionModal.task) {
      onTaskUpdate?.(completionModal.task.id, {
        status: 'done',
        timeTracked: (completionModal.task.timeTracked || 0) + timeSpent,
        isTracking: false
      });
    }
    setCompletionModal({ isOpen: false, task: null });
  };

  return (
    <div ref={containerRef} className="flex flex-col h-[calc(100vh-6rem)] relative">
      {/* Header and Search Filters - Fixed at Top */}
      <div className="flex-none pb-3 mb-2 bg-background/95 backdrop-blur z-40 border-b">
        <div className="space-y-3">
          {/* Title Bar */}
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold" data-testid="text-task-list-title">
              {t('taskList.title')}
            </h2>
            <Badge variant="secondary" data-testid="badge-task-count">
              {t('taskList.taskCount', { count: filteredAndSortedTasks.length })}
            </Badge>
          </div>
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              placeholder={t('taskList.searchPlaceholder')}
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                console.log('Search query:', e.target.value);
              }}
              className="pl-10"
              data-testid="input-search-tasks"
            />
          </div>

          <div className="flex flex-wrap gap-2 sm:gap-3">
            <Select value={filterBy} onValueChange={(value: FilterOption) => {
              setFilterBy(value);
              console.log('Filter changed to:', value);
            }}>
              <SelectTrigger className="flex-1 min-w-0" data-testid="select-filter">
                <div className="flex items-center gap-2 truncate">
                  <Filter className="w-4 h-4 shrink-0" />
                  <SelectValue />
                </div>
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="open">{t('taskList.filter.open')} ({getFilterCount('open')})</SelectItem>
                <SelectItem value="all">{t('taskList.filter.all')} ({getFilterCount('all')})</SelectItem>
                <SelectItem value="todo">{t('taskList.filter.todo')} ({getFilterCount('todo')})</SelectItem>
                <SelectItem value="inProgress">{t('taskList.filter.inProgress')} ({getFilterCount('inProgress')})</SelectItem>
                <SelectItem value="done">{t('taskList.filter.done')} ({getFilterCount('done')})</SelectItem>
                <SelectItem value="overdue">{t('taskList.filter.overdue')} ({getFilterCount('overdue')})</SelectItem>
                <SelectItem value="planned">{t('taskList.filter.planned')} ({getFilterCount('planned')})</SelectItem>
                <SelectItem value="unplanned">{t('taskList.filter.unplanned')} ({getFilterCount('unplanned')})</SelectItem>
              </SelectContent>
            </Select>

            <Select value={filterByLabel} onValueChange={(value: string) => {
              setFilterByLabel(value);
              console.log('Label filter changed to:', value);
            }}>
              <SelectTrigger className="flex-1 min-w-0" data-testid="select-label-filter">
                <div className="flex items-center gap-2 truncate">
                  <Tag className="w-4 h-4 shrink-0" />
                  <SelectValue />
                </div>
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">{t('taskList.filter.allLabels', 'Alle Labels')}</SelectItem>
                {labels.map((label) => (
                  <SelectItem key={label.id} value={label.id}>
                    <div className="flex items-center gap-2">
                      <div
                        className="w-3 h-3 rounded-full shrink-0"
                        style={{ backgroundColor: label.color }}
                      />
                      <span>{label.name}</span>
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select value={sortBy} onValueChange={(value: SortOption) => {
              setSortBy(value);
              console.log('Sort changed to:', value);
            }}>
              <SelectTrigger className="flex-1 min-w-0" data-testid="select-sort">
                <div className="flex items-center gap-2 truncate">
                  <SortAsc className="w-4 h-4 shrink-0" />
                  <SelectValue />
                </div>
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="dueDate">{t('taskList.sort.dueDate')}</SelectItem>
                <SelectItem value="priority">{t('taskList.sort.priority')}</SelectItem>
                <SelectItem value="title">{t('taskList.sort.title')}</SelectItem>
                <SelectItem value="status">{t('taskList.sort.status')}</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      </div>

      {/* Scrollable Task List */}
      <div className="flex-1 overflow-y-auto min-h-0 space-y-3 px-1 pb-4">
        {unscheduledTasks.length === 0 ? (
          <div className="text-center py-8">
            <p className="text-muted-foreground" data-testid="text-no-tasks">
              {searchQuery || (filterBy !== 'all' && filterBy !== 'open')
                ? t('taskList.noMatchingTasks')
                : t('taskList.noUnscheduledTasks')
              }
            </p>
          </div>
        ) : (
          <>
            <div className="text-sm font-medium text-muted-foreground mb-2 mt-2">
              {t('taskList.listHeader')}
            </div>
            {unscheduledTasks.map((task) => (
              <div
                key={task.id}
                draggable
                onDragStart={(e) => handleDragStart(task.id, e)}
                onDragEnd={handleDragEnd}
                className={`cursor-move transition-transform hover-elevate ${draggedTask === task.id ? 'opacity-50 scale-95' : ''
                  }`}
              >
                <TaskCard
                  task={task}
                  onStartTimer={() => onStartTimer?.(task.id)}
                  onStopTimer={() => onStopTimer?.(task.id)}
                  onEdit={() => {
                    onTaskEdit?.(task);
                    console.log(`Edit task ${task.title}`);
                  }}
                  onDelete={() => {
                    onTaskDelete?.(task.id);
                    console.log(`Delete task ${task.title}`);
                  }}
                  onStatusChange={(newStatus) => {
                    if (newStatus === 'done') {
                      handleTaskComplete(task);
                    } else {
                      onTaskUpdate?.(task.id, { status: newStatus });
                    }
                    console.log(`Task ${task.title} status changed to ${newStatus}`);
                  }}
                  onUpdate={(updates) => onTaskUpdate?.(task.id, updates)}
                  isDragging={draggedTask === task.id}
                />
              </div>
            ))}
          </>
        )}
      </div>

      {/* Calendar Section - Fixed at bottom */}
      <div className="flex-none bg-background/95 backdrop-blur z-30 border-t mt-auto shadow-up-lg">
        <div className="p-3">
          {/* Calendar Header */}
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <Calendar className="w-4 h-4 text-primary" />
              <h3 className="text-sm font-semibold" data-testid="text-calendar-title">
                {t('taskList.calendarTitle', { count: visibleDays })}
              </h3>
            </div>

            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="icon"
                onClick={() => navigateCalendar('prev')}
                data-testid="button-prev-week"
              >
                <ChevronLeft className="w-3 h-3" />
              </Button>

              <Button
                variant="outline"
                size="icon"
                onClick={() => navigateCalendar('next')}
                data-testid="button-next-week"
              >
                <ChevronRight className="w-3 h-3" />
              </Button>
            </div>
          </div>

          {/* Full Width Calendar Grid - Dynamic */}
          <div className={`grid gap-2`} style={{ gridTemplateColumns: `repeat(${visibleDays}, minmax(0, 1fr))` }}>
            {dates.map((date, index) => {
              // Sort by priority to ensure high priority items are shown first
              const dayTasks = getTasksForDate(date).sort((a, b) => {
                const priorityOrder = { high: 3, medium: 2, low: 1 };
                return (priorityOrder[b.priority as keyof typeof priorityOrder] || 0) - (priorityOrder[a.priority as keyof typeof priorityOrder] || 0);
              });
              const isToday = isSameDay(date, new Date());
              const isWeekend = date.getDay() === 0 || date.getDay() === 6;
              const isHovered = hoveredDate && isSameDay(date, hoveredDate);


              // Use important modifier to ensure weekend styling overrides any conflicting CSS
              const weekendClasses = isWeekend ? '!bg-muted/80 border-muted-foreground/30 shadow-sm' : '';
              const todayClasses = isToday ? 'border-primary ring-1 ring-primary ring-offset-1 ring-offset-background' : 'border-border';
              const hoverClasses = isHovered && draggedTask ? 'ring-2 ring-primary bg-primary/15 border-primary shadow-lg' : '';
              const dragClasses = draggedTask && !isHovered ? 'border-dashed border-primary/30' : '';

              const finalClassName = `p-2 sm:p-2 min-h-[140px] sm:min-h-[100px] transition-all border-2 ${todayClasses} ${weekendClasses} ${hoverClasses} ${dragClasses}`;

              return (
                <Card
                  key={index}
                  className={finalClassName}
                  onDragOver={handleDragOver}
                  onDragEnter={() => handleDragEnter(date)}
                  onDragLeave={handleDragLeave}
                  onMouseMove={(e) => handleMouseMove(e, date)}
                  onDrop={(e) => handleDrop(date, e)}
                  onClick={() => {
                    console.log('Date selected:', date.toLocaleDateString());
                  }}
                  data-testid={`calendar-date-${format(date, 'yyyy-MM-dd')}`}
                >
                  <div className="text-center mb-2">
                    <div className={`text-xs sm:text-xs font-medium ${isWeekend ? 'text-muted-foreground font-semibold' : 'text-muted-foreground'
                      }`}>
                      {format(date, 'EEE', { locale: dateLocale })}
                    </div>
                    <div className={`text-sm sm:text-xs font-semibold ${isToday ? 'text-primary' : isWeekend ? 'text-primary/80' : ''
                      }`}>
                      {format(date, 'd', { locale: dateLocale })}
                    </div>
                  </div>

                  <div className="space-y-1">
                    {dayTasks.slice(0, 2).map((task) => {
                      // Find the label for this task
                      const taskLabel = task.labelId && labels.length > 0 ? labels.find(label => label.id === task.labelId) : null;

                      return (
                        <ContextMenu key={task.id}>
                          <ContextMenuTrigger asChild>
                            <div
                              draggable
                              onDragStart={(e) => handleDragStart(task.id, e)}
                              onDragEnd={handleDragEnd}
                              onClick={(e) => {
                                // Prevent click when dragging
                                if (draggedTask === task.id) return;
                                e.stopPropagation();
                                onTaskEdit?.(task);
                                console.log('Calendar task clicked:', task.title);
                              }}
                              className={`cursor-pointer hover-elevate ${draggedTask === task.id ? 'opacity-50' : ''}`}
                              data-testid={`calendar-task-${task.id}`}
                            >
                              <Badge
                                variant="outline"
                                className="w-full justify-start text-xs p-1 sm:p-1 py-2 sm:py-1 h-auto text-left"
                                style={taskLabel ? {
                                  borderColor: taskLabel.color,
                                  borderWidth: '2px',
                                  borderStyle: 'solid'
                                } : {}}
                              >
                                <div className="truncate text-sm sm:text-xs pointer-events-none">
                                  {task.title}
                                </div>
                              </Badge>
                            </div>
                          </ContextMenuTrigger>
                          <ContextMenuContent>
                            <ContextMenuItem
                              onClick={(e) => {
                                e.stopPropagation();
                                onTaskEdit?.(task);
                              }}
                              data-testid={`mini-context-menu-edit-${task.id}`}
                            >
                              <Edit className="w-4 h-4 mr-2" />
                              {t('taskCard.editTask')}
                            </ContextMenuItem>

                            <ContextMenuItem
                              onClick={(e) => {
                                e.stopPropagation();
                                if (task.isTracking) {
                                  onStopTimer?.(task.id);
                                } else {
                                  onStartTimer?.(task.id);
                                }
                              }}
                              data-testid={`mini-context-menu-timer-${task.id}`}
                            >
                              <Timer className="w-4 h-4 mr-2" />
                              {task.isTracking ? t('taskCard.stopTimer') : t('taskCard.startTimer')}
                            </ContextMenuItem>

                            <ContextMenuSeparator />

                            {task.status !== 'done' && (
                              <ContextMenuItem
                                onClick={(e) => {
                                  e.stopPropagation();
                                  const taskToComplete = tasks.find(t => t.id === task.id);
                                  if (taskToComplete) {
                                    handleTaskComplete(taskToComplete);
                                  }
                                }}
                                data-testid={`mini-context-menu-complete-${task.id}`}
                              >
                                <CheckCircle className="w-4 h-4 mr-2" />
                                {t('taskCard.markAsDone')}
                              </ContextMenuItem>
                            )}

                            {task.status === 'todo' && (
                              <ContextMenuItem
                                onClick={(e) => {
                                  e.stopPropagation();
                                  onTaskUpdate?.(task.id, { status: 'inProgress' });
                                }}
                                data-testid={`mini-context-menu-start-${task.id}`}
                              >
                                <Play className="w-4 h-4 mr-2" />
                                {t('taskCard.startWorking')}
                              </ContextMenuItem>
                            )}

                            {task.status === 'inProgress' && (
                              <ContextMenuItem
                                onClick={(e) => {
                                  e.stopPropagation();
                                  onTaskUpdate?.(task.id, { status: 'todo' });
                                }}
                                data-testid={`mini-context-menu-todo-${task.id}`}
                              >
                                <Clock className="w-4 h-4 mr-2" />
                                {t('taskCard.moveToTodo')}
                              </ContextMenuItem>
                            )}

                            {task.status === 'done' && (
                              <ContextMenuItem
                                onClick={(e) => {
                                  e.stopPropagation();
                                  onTaskUpdate?.(task.id, { status: 'inProgress' });
                                }}
                                data-testid={`mini-context-menu-reopen-${task.id}`}
                              >
                                <Play className="w-4 h-4 mr-2" />
                                {t('taskCard.reopenTask')}
                              </ContextMenuItem>
                            )}

                            <ContextMenuSeparator />

                            {onTaskDelete && (
                              <ContextMenuItem
                                onClick={(e) => {
                                  e.stopPropagation();
                                  onTaskDelete(task.id);
                                }}
                                className="text-destructive"
                                data-testid={`mini-context-menu-delete-${task.id}`}
                              >
                                <Trash2 className="w-4 h-4 mr-2" />
                                {t('taskCard.deleteTask')}
                              </ContextMenuItem>
                            )}
                          </ContextMenuContent>
                        </ContextMenu>
                      );
                    })}

                    {dayTasks.length > 2 && (
                      <HoverCard openDelay={0} closeDelay={100}>
                        <HoverCardTrigger asChild>
                          <Badge variant="secondary" className="w-full justify-center text-sm sm:text-xs py-1 sm:py-0 cursor-pointer hover:bg-secondary/80">
                            +{dayTasks.length - 2} more
                          </Badge>
                        </HoverCardTrigger>
                        <HoverCardContent className="w-72 p-0" side="top">
                          <div className="p-3 border-b bg-muted/30">
                            <h4 className="font-semibold text-xs text-muted-foreground flex items-center justify-between">
                              <span>{t('calendar.moreItems', { count: dayTasks.length - 2 })}</span>
                              <span className="text-[10px] font-normal opacity-75">{t('calendar.clickToEdit')}</span>
                            </h4>
                          </div>
                          <div className="max-h-[300px] overflow-y-auto p-2 space-y-1">
                            {dayTasks.slice(2).map(task => {
                              const taskLabel = task.labelId && labels.length > 0 ? labels.find(label => label.id === task.labelId) : null;
                              return (
                                <div
                                  key={task.id}
                                  className="p-2 border rounded hover:bg-accent cursor-pointer flex items-center justify-between group transition-colors"
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    onTaskEdit?.(task);
                                  }}
                                >
                                  <div className="min-w-0 flex-1 mr-2">
                                    <div className="text-xs font-medium truncate">{task.title}</div>
                                    {taskLabel && (
                                      <div className="flex items-center gap-1 mt-1">
                                        <div className="w-2 h-2 rounded-full" style={{ backgroundColor: taskLabel.color }} />
                                        <span className="text-[10px] text-muted-foreground truncate max-w-[100px]">{taskLabel.name}</span>
                                      </div>
                                    )}
                                  </div>
                                  <Button size="icon" variant="ghost" className="h-6 w-6 opacity-0 group-hover:opacity-100 shrink-0" onClick={(e) => {
                                    e.stopPropagation();
                                    onTaskEdit?.(task);
                                  }}>
                                    <Edit className="w-3 h-3" />
                                  </Button>
                                </div>
                              )
                            })}
                          </div>
                        </HoverCardContent>
                      </HoverCard>
                    )}

                    {dayTasks.length === 0 && (
                      <div className={`text-center text-xs py-2 rounded border border-dashed transition-all ${isHovered && draggedTask
                        ? 'border-primary text-primary bg-primary/5'
                        : draggedTask
                          ? 'border-primary/50 text-primary/70'
                          : 'border-muted-foreground/30 text-muted-foreground'
                        }`}>
                        {isHovered && draggedTask ? t('calendar.dropHere') : draggedTask ? t('calendar.drop') : ''}
                      </div>
                    )}
                  </div>
                </Card>
              );
            })}
          </div>
        </div>
      </div>

      {/* Spacer */}
      <div className="h-4" />

      {/* Time Completion Modal */}
      <TimeCompletionModal
        isOpen={completionModal.isOpen}
        onClose={() => setCompletionModal({ isOpen: false, task: null })}
        onSave={handleTimeLogged}
        taskTitle={completionModal.task?.title || ''}
      />
    </div>
  );
}