import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Clock, Calendar, Play, Pause, MoreHorizontal, Edit, Trash2, Timer, CheckCircle } from "lucide-react";
import { Task, Label } from '@shared/schema';
import { useQuery } from '@tanstack/react-query';

interface TaskCardProps {
  task: Task;
  onStartTimer?: () => void;
  onStopTimer?: () => void;
  onEdit?: () => void;
  onDelete?: () => void;
  onStatusChange?: (status: Task['status']) => void;
  isDragging?: boolean;
}

export default function TaskCard({ task, onStartTimer, onStopTimer, onEdit, onDelete, onStatusChange, isDragging }: TaskCardProps) {

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

  // Find the label for this task
  const taskLabel = task.labelId && labels.length > 0 ? labels.find(label => label.id === task.labelId) : null;

  const handleToggleTimer = () => {
    if (task.isTracking) {
      onStopTimer?.();
      console.log(`Timer stopped for task: ${task.title}`);
    } else {
      onStartTimer?.();
      console.log(`Timer started for task: ${task.title}`);
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'high': return 'bg-destructive text-destructive-foreground';
      case 'medium': return 'bg-yellow-500 text-white';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'done': return 'bg-green-500 text-white';
      case 'inProgress': return 'bg-primary text-primary-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const formatTime = (minutes: number) => {
    if (minutes < 60) {
      return `${minutes}m`;
    }
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    if (mins === 0) {
      return `${hours}h`;
    }
    return `${hours}h ${mins}m`;
  };

  return (
    <Card 
      className={`p-4 hover-elevate active-elevate-2 transition-all duration-200 relative cursor-pointer ${
        isDragging ? 'rotate-1 scale-105 shadow-lg' : ''
      }`}
      style={taskLabel ? { 
        borderColor: taskLabel.color,
        borderWidth: '2px',
        borderStyle: 'solid'
      } : {}}
      data-testid={`card-task-${task.id}`}
      onClick={() => {
        onEdit?.();
        console.log(`Task card clicked: ${task.title}`);
      }}
    >
      <div className="flex items-start justify-between gap-3">
        <div className="flex-1 min-w-0">
          <h3 className="font-medium text-sm leading-tight truncate" data-testid={`text-task-title-${task.id}`}>
            {task.title}
          </h3>
          {task.description && (
            <p className="text-xs text-muted-foreground mt-1 line-clamp-2" data-testid={`text-task-description-${task.id}`}>
              {task.description}
            </p>
          )}
          
          <div className="flex items-center gap-2 mt-3 flex-wrap">
            <Badge 
              variant="secondary" 
              className={`text-xs ${getPriorityColor(task.priority)}`}
              data-testid={`badge-priority-${task.id}`}
            >
              {task.priority}
            </Badge>
            
            <Badge 
              variant="outline" 
              className={`text-xs ${getStatusColor(task.status)}`}
              data-testid={`badge-status-${task.id}`}
            >
              {task.status.replace(/([A-Z])/g, ' $1').toLowerCase()}
            </Badge>

            {task.dueDate && (
              <div className="flex items-center gap-1 text-xs text-muted-foreground">
                <Calendar className="w-3 h-3" />
                <span data-testid={`text-due-date-${task.id}`}>
                  {task.dueDate.toLocaleDateString()}
                </span>
              </div>
            )}
          </div>

          {(task.timeTracked > 0 || task.isTracking) && (
            <div className="flex items-center gap-1 mt-2 text-xs">
              <Clock className={`w-3 h-3 ${task.isTracking ? 'text-primary animate-pulse' : 'text-muted-foreground'}`} />
              <span 
                data-testid={`text-time-tracked-${task.id}`}
                className={task.isTracking ? 'text-primary font-medium' : 'text-muted-foreground'}
              >
                {task.timeTracked > 0 ? formatTime(task.timeTracked) : '0m'}
                {task.isTracking && ' (running)'}
              </span>
            </div>
          )}
        </div>

        <div className="flex flex-col gap-2">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button
                size="icon"
                variant="ghost"
                onClick={(e) => e.stopPropagation()}
                data-testid={`button-menu-${task.id}`}
                className="w-6 h-6"
              >
                <MoreHorizontal className="w-3 h-3" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
              <DropdownMenuItem 
                onClick={(e) => {
                  e.stopPropagation();
                  onEdit?.();
                  console.log(`Edit task: ${task.title}`);
                }}
                data-testid={`menu-edit-${task.id}`}
              >
                <Edit className="w-4 h-4 mr-2" />
                Edit Task
              </DropdownMenuItem>
              
              <DropdownMenuItem 
                onClick={(e) => {
                  e.stopPropagation();
                  handleToggleTimer();
                }}
                data-testid={`menu-timer-${task.id}`}
              >
                <Timer className="w-4 h-4 mr-2" />
                {task.isTracking ? 'Stop Timer' : 'Start Timer'}
              </DropdownMenuItem>
              
              <DropdownMenuSeparator />
              
              {task.status !== 'done' && (
                <DropdownMenuItem 
                  onClick={(e) => {
                    e.stopPropagation();
                    onStatusChange?.('done');
                    console.log(`Mark task as done: ${task.title}`);
                  }}
                  data-testid={`menu-complete-${task.id}`}
                >
                  <CheckCircle className="w-4 h-4 mr-2" />
                  Mark as Done
                </DropdownMenuItem>
              )}
              
              {task.status === 'todo' && (
                <DropdownMenuItem 
                  onClick={(e) => {
                    e.stopPropagation();
                    onStatusChange?.('inProgress');
                    console.log(`Start working on: ${task.title}`);
                  }}
                  data-testid={`menu-start-${task.id}`}
                >
                  <Play className="w-4 h-4 mr-2" />
                  Start Working
                </DropdownMenuItem>
              )}
              
              {task.status === 'inProgress' && (
                <DropdownMenuItem 
                  onClick={(e) => {
                    e.stopPropagation();
                    onStatusChange?.('todo');
                    console.log(`Move back to todo: ${task.title}`);
                  }}
                  data-testid={`menu-todo-${task.id}`}
                >
                  <Clock className="w-4 h-4 mr-2" />
                  Move to Todo
                </DropdownMenuItem>
              )}
              
              {task.status === 'done' && (
                <DropdownMenuItem 
                  onClick={(e) => {
                    e.stopPropagation();
                    onStatusChange?.('inProgress');
                    console.log(`Reopen task: ${task.title}`);
                  }}
                  data-testid={`menu-reopen-${task.id}`}
                >
                  <Play className="w-4 h-4 mr-2" />
                  Reopen Task
                </DropdownMenuItem>
              )}
              
              <DropdownMenuSeparator />
              
              {onDelete && (
                <DropdownMenuItem 
                  onClick={(e) => {
                    e.stopPropagation();
                    onDelete();
                    console.log(`Delete task: ${task.title}`);
                  }}
                  className="text-destructive"
                  data-testid={`menu-delete-${task.id}`}
                >
                  <Trash2 className="w-4 h-4 mr-2" />
                  Delete Task
                </DropdownMenuItem>
              )}
            </DropdownMenuContent>
          </DropdownMenu>
          
          <Button
            size="icon"
            variant={task.isTracking ? "default" : "outline"}
            onClick={(e) => {
              e.stopPropagation();
              handleToggleTimer();
            }}
            data-testid={`button-timer-${task.id}`}
            className="w-6 h-6"
          >
            {task.isTracking ? <Pause className="w-3 h-3" /> : <Play className="w-3 h-3" />}
          </Button>
        </div>
      </div>
    </Card>
  );
}