import { useState } from "react";
import { MoreHorizontalIcon } from "lucide-react";

import { DottedSeparator } from "@/components/dotted-separator";
import { MemberAvatar } from "@/features/members/components/member-avatar";
import { ProjectAvatar } from "@/features/projects/components/project-avatar";

import { Task } from "../types";
import { TaskDate } from "./task-date";
import { TaskActions } from "./task-actions";
import { TaskDetailsModal } from "./task-details-modal";

interface KanbanCardProps {
  task: Task;
}

export const KanbanCard = ({ task }: KanbanCardProps) => {
  const [isModalOpen, setIsModalOpen] = useState(false);

  const handleCardClick = (e: React.MouseEvent) => {
    // Don't open modal if clicking on the actions button
    if ((e.target as HTMLElement).closest('[data-task-actions]')) {
      return;
    }
    setIsModalOpen(true);
  };

  return (
    <>
      <div 
        className="bg-white p-2.5 mb-1.5 rounded shadow-md space-y-3 cursor-pointer hover:shadow-lg transition-shadow"
        onClick={handleCardClick}
      >
        <div className="flex items-start justify-between gap-x-2">
          <p className="text-sm line-clamp-2">{task.name}</p>
          <div data-task-actions>
            <TaskActions id={task.id} projectId={task.projectId || ""}>
              <MoreHorizontalIcon className="size-[18px] stroke-1 shrink-0 text-neutral-700 hover:opacity-75 transition" />
            </TaskActions>
          </div>
        </div>
        <DottedSeparator />
        <div className="flex items-center gap-x-1.5">
          <MemberAvatar
            name={task.assignee?.name || "Unassigned"}
            fallbackClassName="text-[10px]"
          />
          <div className="size-1 rounded-full bg-neutral-300" />
          <TaskDate value={task.dueDate ? (typeof task.dueDate === 'string' ? task.dueDate : task.dueDate.toISOString()) : ""} className="text-xs" />
        </div>
        <div className="flex items-center gap-x-1.5">
          <ProjectAvatar
            name={task.project?.name || "No project"}
            image={task.project?.imageUrl || ""}
            fallbackClassName="text-[10px]"
          />
          <span className="text-xs font-medium" style={{
            wordBreak: "break-all"
          }}>
            {task.project?.name 
              ? task.project.name.length > 80 
                ? task.project.name.slice(0, 10) + "..." 
                : task.project.name 
              : "No project"
            }
          </span>
        </div>
      </div>
      
      <TaskDetailsModal
        taskId={task.id}
        open={isModalOpen}
        onOpenChange={setIsModalOpen}
      />
    </>
  );
};
