"use client";

import React from "react";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Edit, Trash2 } from "lucide-react";
import { cn } from "@/lib/utils";
import { useUpdateCode } from "@/hooks/queries/useCodes";
import type { CodeInfo } from "@/types/commonCode";

interface SortableCodeItemProps {
  code: CodeInfo;
  categoryCode: string;
  onEdit: () => void;
  onDelete: () => void;
  isDragOverlay?: boolean;
}

export function SortableCodeItem({
  code,
  categoryCode,
  onEdit,
  onDelete,
  isDragOverlay = false,
}: SortableCodeItemProps) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
    id: code.codeValue || code.code_value,
    disabled: isDragOverlay,
  });
  const updateCodeMutation = useUpdateCode();

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
  };

  // 활성/비활성 토글 핸들러
  const handleToggleActive = async (checked: boolean) => {
    try {
      // codeValue 또는 code_value가 없으면 에러 처리
      const codeValue = code.codeValue || code.code_value;
      if (!codeValue) {
        return;
      }

      await updateCodeMutation.mutateAsync({
        categoryCode,
        codeValue: codeValue,
        data: {
          codeName: code.codeName || code.code_name,
          codeNameEng: code.codeNameEng || code.code_name_eng || "",
          description: code.description || "",
          sortOrder: code.sortOrder || code.sort_order,
          isActive: checked ? "Y" : "N",
        },
      });
    } catch (error) {
      console.error("코드 활성 상태 변경 실패:", error);
    }
  };

  return (
    <div
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
      className={cn(
        "group cursor-grab rounded-lg border bg-card p-4 shadow-sm transition-all hover:shadow-md",
        isDragging && "cursor-grabbing opacity-50",
      )}
    >
      <div className="flex items-start justify-between gap-2">
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2">
            <h4 className="text-sm font-semibold">{code.codeName || code.code_name}</h4>
            <Badge
              variant={code.isActive === "Y" || code.is_active === "Y" ? "default" : "secondary"}
              className={cn(
                "cursor-pointer text-xs transition-colors",
                updateCodeMutation.isPending && "cursor-not-allowed opacity-50",
              )}
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                if (!updateCodeMutation.isPending) {
                  const isActive = code.isActive === "Y" || code.is_active === "Y";
                  handleToggleActive(!isActive);
                }
              }}
              onPointerDown={(e) => e.stopPropagation()}
              onMouseDown={(e) => e.stopPropagation()}
            >
              {code.isActive === "Y" || code.is_active === "Y" ? "활성" : "비활성"}
            </Badge>
          </div>
          <p className="mt-1 text-xs text-muted-foreground">{code.codeValue || code.code_value}</p>
          {code.description && <p className="mt-1 text-xs text-muted-foreground">{code.description}</p>}
        </div>

        {/* 액션 버튼 */}
        <div
          className="flex items-center gap-1"
          onPointerDown={(e) => e.stopPropagation()}
          onMouseDown={(e) => e.stopPropagation()}
        >
          <Button
            variant="ghost"
            size="sm"
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              onEdit();
            }}
          >
            <Edit className="h-3 w-3" />
          </Button>
          <Button
            variant="ghost"
            size="sm"
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              onDelete();
            }}
          >
            <Trash2 className="h-3 w-3" />
          </Button>
        </div>
      </div>
    </div>
  );
}
