import { useTransition, useState } from 'react';
import { Task } from '@/lib/types';
import { TaskCard as UITaskCard, ConfirmModal } from '@/components/ui';
import { useTasksContext } from '@/contexts/TasksContext';
import { useUserPreferences } from '@/contexts/UserPreferencesContext';
import { useDraggable } from '@dnd-kit/core';
import { updateTaskTitle, deleteTask } from '@/actions/tasks';

interface TaskCardProps {
  task: Task;
  onEdit?: (task: Task) => void;
  compactView?: boolean;
}

export function TaskCard({ task, onEdit, compactView = false }: TaskCardProps) {
  const [isPending, startTransition] = useTransition();
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const { tags: availableTags, refreshTasks } = useTasksContext();
  const { preferences } = useUserPreferences();

  // Configuration du draggable
  const { attributes, listeners, setNodeRef, transform, isDragging } =
    useDraggable({
      id: task.id,
    });

  const handleDelete = () => {
    setShowDeleteConfirm(true);
  };

  const confirmDelete = async () => {
    startTransition(async () => {
      const result = await deleteTask(task.id);
      if (!result.success) {
        console.error('Error deleting task:', result.error);
      } else {
        await refreshTasks();
      }
    });
  };

  const handleEdit = () => {
    if (onEdit) {
      onEdit(task);
    }
  };

  const handleTitleSave = async (newTitle: string) => {
    startTransition(async () => {
      const result = await updateTaskTitle(task.id, newTitle);
      if (!result.success) {
        console.error('Error updating task title:', result.error);
      } else {
        task.title = newTitle;
      }
    });
  };

  // Style de transformation pour le drag
  const style = transform
    ? {
        transform: `translate3d(${transform.x}px, ${transform.y}px, 0)`,
      }
    : undefined;

  return (
    <>
      <UITaskCard
        ref={setNodeRef}
        style={style}
        variant={compactView ? 'compact' : 'detailed'}
        source={task.source || 'manual'}
        title={task.title}
        description={task.description}
        tags={task.tags}
        primaryTagId={task.primaryTagId}
        priority={task.priority}
        status={task.status}
        dueDate={task.dueDate}
        completedAt={task.completedAt}
        jiraKey={task.jiraKey}
        jiraProject={task.jiraProject}
        jiraType={task.jiraType}
        tfsPullRequestId={task.tfsPullRequestId}
        tfsProject={task.tfsProject}
        tfsRepository={task.tfsRepository}
        todosCount={task.todosCount}
        isDragging={isDragging}
        isPending={isPending}
        onEdit={handleEdit}
        onDelete={handleDelete}
        onTitleSave={handleTitleSave}
        fontSize={preferences.viewPreferences.fontSize}
        availableTags={availableTags}
        jiraConfig={preferences.jiraConfig}
        tfsConfig={preferences.tfsConfig}
        {...attributes}
        {...listeners}
      />

      <ConfirmModal
        isOpen={showDeleteConfirm}
        onClose={() => setShowDeleteConfirm(false)}
        onConfirm={confirmDelete}
        title="Supprimer la tâche"
        message="Êtes-vous sûr de vouloir supprimer cette tâche ? Cette action est irréversible."
        confirmText="Supprimer"
        cancelText="Annuler"
        variant="destructive"
        isLoading={isPending}
      />
    </>
  );
}
