"use client";

import { useState } from "react";
import { Task, WorkItemStatus } from "@/types/project";
import { useChangeTaskStatus, useUpdateTask, useDeleteTask } from "@/lib/hooks/use-tasks";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { MoreHorizontal, Pencil, Trash2, Clock, User, CheckCircle2, Circle } from "lucide-react";
import { cn } from "@/lib/utils";
import { TaskEditDialog } from "./task-edit-dialog";

interface TaskCardProps {
  task: Task;
  storyId: string;
}

const priorityColors = {
  Critical: "bg-red-500 text-white",
  High: "bg-orange-500 text-white",
  Medium: "bg-yellow-500 text-white",
  Low: "bg-blue-500 text-white",
};

const statusColors = {
  Backlog: "text-slate-500",
  Todo: "text-gray-500",
  InProgress: "text-blue-500",
  Done: "text-green-500",
  Blocked: "text-red-500",
};

export function TaskCard({ task, storyId }: TaskCardProps) {
  const [isExpanded, setIsExpanded] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const changeStatus = useChangeTaskStatus();
  const updateTask = useUpdateTask();
  const deleteTask = useDeleteTask();

  const isDone = task.status === "Done";

  const handleCheckboxChange = (checked: boolean) => {
    const newStatus: WorkItemStatus = checked ? "Done" : "Todo";
    changeStatus.mutate({ id: task.id, status: newStatus });
  };

  const handleDelete = () => {
    if (confirm("Are you sure you want to delete this task?")) {
      deleteTask.mutate(task.id);
    }
  };

  return (
    <Card
      className={cn(
        "cursor-pointer transition-all duration-200 hover:shadow-md",
        isDone && "opacity-60"
      )}
      onClick={() => setIsExpanded(!isExpanded)}
    >
      <CardHeader className="p-4">
        <div className="flex items-start gap-3">
          {/* Checkbox */}
          <div onClick={(e) => e.stopPropagation()}>
            <Checkbox
              checked={isDone}
              onCheckedChange={handleCheckboxChange}
              disabled={changeStatus.isPending}
              className="mt-1"
            />
          </div>

          {/* Task Content */}
          <div className="min-w-0 flex-1">
            <div className="mb-2 flex items-center gap-2">
              <h4
                className={cn(
                  "text-sm font-medium",
                  isDone && "text-muted-foreground line-through"
                )}
              >
                {task.title}
              </h4>
              <Badge variant="secondary" className={cn("text-xs", priorityColors[task.priority])}>
                {task.priority}
              </Badge>
            </div>

            {/* Metadata */}
            <div className="text-muted-foreground flex items-center gap-4 text-xs">
              {task.estimatedHours && (
                <div className="flex items-center gap-1">
                  <Clock className="h-3 w-3" />
                  <span>{task.estimatedHours}h</span>
                </div>
              )}
              {task.assigneeId && (
                <div className="flex items-center gap-1">
                  <User className="h-3 w-3" />
                  <span>Assigned</span>
                </div>
              )}
              <div className={cn("flex items-center gap-1", statusColors[task.status])}>
                {isDone ? <CheckCircle2 className="h-3 w-3" /> : <Circle className="h-3 w-3" />}
                <span>{task.status}</span>
              </div>
            </div>

            {/* Description (expanded) */}
            {isExpanded && task.description && (
              <div className="text-muted-foreground mt-3 text-sm">{task.description}</div>
            )}
          </div>

          {/* Actions Menu */}
          <div onClick={(e) => e.stopPropagation()}>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                  <MoreHorizontal className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={() => setIsEditDialogOpen(true)}>
                  <Pencil className="mr-2 h-4 w-4" />
                  Edit
                </DropdownMenuItem>
                <DropdownMenuItem onClick={handleDelete} className="text-destructive">
                  <Trash2 className="mr-2 h-4 w-4" />
                  Delete
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </CardHeader>

      {/* Edit Dialog */}
      <TaskEditDialog task={task} open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen} />
    </Card>
  );
}
