"use client";

import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { GripVertical, X } from "lucide-react";
import { getQuestionTypeLabel } from "@/config/question-types";
import {
  QuestionCardShell,
  QuestionPreviewBody,
} from "@/components/features/surveys/QuestionPreviewBody";
import { Button } from "@/components/ui/Button";
import type { BuilderQuestion } from "@/types/builder";

interface SortableQuestionCardProps {
  question: BuilderQuestion;
  index: number;
  selected: boolean;
  onSelect: () => void;
  onDelete: () => void;
}

export function SortableQuestionCard({
  question,
  index,
  selected,
  onSelect,
  onDelete,
}: SortableQuestionCardProps) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: question.id });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  return (
    <div ref={setNodeRef} style={style}>
      <QuestionCardShell selected={selected} onClick={onSelect}>
        <div className="mb-3 flex items-start justify-between gap-2">
          <div className="flex min-w-0 flex-1 items-start gap-2">
            <button
              type="button"
              className="mt-0.5 shrink-0 cursor-grab touch-none text-muted hover:text-primary active:cursor-grabbing"
              {...attributes}
              {...listeners}
              onClick={(e) => e.stopPropagation()}
              aria-label="Drag to reorder"
            >
              <GripVertical className="h-4 w-4" />
            </button>
            <div className="min-w-0">
              <div className="font-mono text-[11px] font-bold text-muted">
                QUESTION {index + 1}
              </div>
              <div className="mt-1 text-sm font-bold leading-snug">
                {question.title}
              </div>
            </div>
          </div>
          <div className="flex shrink-0 items-center gap-2">
            <span className="rounded-xl bg-[#EFF6FF] px-2 py-0.5 text-[10.5px] font-bold text-primary">
              {getQuestionTypeLabel(question.type)}
            </span>
            <Button
              variant="icon"
              size="row"
              type="button"
              className="border-none shadow-none hover:text-danger"
              onClick={(e) => {
                e.stopPropagation();
                onDelete();
              }}
              aria-label="Delete question"
            >
              <X className="h-3.5 w-3.5" />
            </Button>
          </div>
        </div>
        <QuestionPreviewBody
          type={question.type}
          optionsConfig={question.optionsConfig}
        />
      </QuestionCardShell>
    </div>
  );
}
