"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, CornerDownRight, Plus, ChevronRight, ChevronDown } 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;
  onAddChild: () => void; // 하위 코드 추가
  isDragOverlay?: boolean;
  maxDepth?: number; // 최대 깊이 (기본값 3)
  hasChildren?: boolean; // 자식이 있는지 여부
  childCount?: number; // 자식 개수
  isExpanded?: boolean; // 펼쳐진 상태
  onToggleExpand?: () => void; // 접기/펼치기 토글
}

export function SortableCodeItem({
  code,
  categoryCode,
  onEdit,
  onDelete,
  onAddChild,
  isDragOverlay = false,
  maxDepth = 3,
  hasChildren = false,
  childCount = 0,
  isExpanded = true,
  onToggleExpand,
}: 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 {
      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);
    }
  };

  // 계층구조 깊이에 따른 들여쓰기
  const depth = code.depth || 1;
  const indentLevel = (depth - 1) * 16; // 16px per level (was 28)
  const hasParent = !!(code.parentCodeValue || code.parent_code_value);
  const isActive = code.isActive === "Y" || code.is_active === "Y";

  return (
    <div className="flex items-stretch">
      {/* 계층구조 들여쓰기 영역 */}
      {depth > 1 && (
        <div
          className="flex items-center justify-end pr-1"
          style={{ width: `${indentLevel}px`, minWidth: `${indentLevel}px` }}
        >
          <CornerDownRight className="h-3 w-3 text-muted-foreground/50" />
        </div>
      )}

      <div
        ref={setNodeRef}
        style={style}
        {...attributes}
        {...listeners}
        className={cn(
          "group flex-1 cursor-grab rounded-md border bg-card px-2.5 py-1.5 transition-colors hover:bg-muted/40",
          isDragging && "cursor-grabbing opacity-50 shadow-md",
          depth === 1 && "border-l-2 border-l-primary",
          depth === 2 && "border-l-2 border-l-blue-400",
          depth === 3 && "border-l-2 border-l-emerald-400",
        )}
      >
        <div className="flex items-center justify-between gap-2">
          <div className="flex min-w-0 flex-1 items-center gap-1.5">
            {/* 접기/펼치기 버튼 */}
            {hasChildren && onToggleExpand ? (
              <button
                type="button"
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  onToggleExpand();
                }}
                onPointerDown={(e) => e.stopPropagation()}
                onMouseDown={(e) => e.stopPropagation()}
                className="flex h-4 w-4 flex-shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
                title={isExpanded ? "접기" : "펼치기"}
              >
                {isExpanded ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />}
              </button>
            ) : (
              <div className="h-4 w-4 flex-shrink-0" />
            )}

            {/* 활성 토글 (점) */}
            <button
              type="button"
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                if (!updateCodeMutation.isPending) handleToggleActive(!isActive);
              }}
              onPointerDown={(e) => e.stopPropagation()}
              onMouseDown={(e) => e.stopPropagation()}
              className={cn(
                "h-1.5 w-1.5 flex-shrink-0 rounded-full transition-colors",
                isActive ? "bg-emerald-500" : "bg-muted-foreground/40",
                updateCodeMutation.isPending && "opacity-50",
              )}
              title={isActive ? "활성 (클릭하여 비활성)" : "비활성 (클릭하여 활성)"}
            />

            {/* 코드명 */}
            <span className="truncate text-[13px] font-medium" title={code.codeName || code.code_name}>
              {code.codeName || code.code_name}
            </span>

            {/* 코드값 (mono) */}
            <span className="hidden flex-shrink-0 font-mono text-[10px] text-muted-foreground sm:inline">
              {code.codeValue || code.code_value}
            </span>

            {/* 자식 개수(접힌 경우) */}
            {hasChildren && !isExpanded && (
              <span className="flex-shrink-0 text-[10px] text-muted-foreground">({childCount})</span>
            )}

            {/* 깊이 배지 — 1단계만 표시 (덜 어수선) */}
            {depth === 1 && (
              <Badge
                variant="outline"
                className="ml-1 flex-shrink-0 border-primary/30 bg-primary/5 px-1 py-0 text-[9px] font-medium text-primary"
              >
                대분류
              </Badge>
            )}
            {depth === 2 && (
              <Badge
                variant="outline"
                className="ml-1 flex-shrink-0 border-blue-300 bg-blue-50 px-1 py-0 text-[9px] font-medium text-blue-700 dark:bg-blue-950/20"
              >
                중분류
              </Badge>
            )}
            {depth === 3 && (
              <Badge
                variant="outline"
                className="ml-1 flex-shrink-0 border-emerald-300 bg-emerald-50 px-1 py-0 text-[9px] font-medium text-emerald-700 dark:bg-emerald-950/20"
              >
                소분류
              </Badge>
            )}
            {depth > 3 && (
              <Badge variant="outline" className="ml-1 flex-shrink-0 px-1 py-0 text-[9px]">
                L{depth}
              </Badge>
            )}
          </div>

          {/* 액션 — hover 시 노출 */}
          <div
            className="flex flex-shrink-0 items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100"
            onPointerDown={(e) => e.stopPropagation()}
            onMouseDown={(e) => e.stopPropagation()}
          >
            {depth < maxDepth && (
              <Button
                variant="ghost"
                size="icon"
                className="h-6 w-6 text-primary hover:bg-primary/10"
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  onAddChild();
                }}
                title="하위 코드 추가"
              >
                <Plus className="h-3 w-3" />
              </Button>
            )}
            <Button
              variant="ghost"
              size="icon"
              className="h-6 w-6"
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                onEdit();
              }}
              title="수정"
            >
              <Edit className="h-3 w-3" />
            </Button>
            <Button
              variant="ghost"
              size="icon"
              className="h-6 w-6 text-destructive hover:bg-destructive/10"
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                onDelete();
              }}
              title="삭제"
            >
              <Trash2 className="h-3 w-3" />
            </Button>
          </div>
        </div>

        {/* 부모 표시(있을 때만, 한 줄) */}
        {hasParent && (
          <p className="ml-7 mt-0.5 truncate font-mono text-[10px] text-muted-foreground">
            ↳ {code.parentCodeValue || code.parent_code_value}
          </p>
        )}
        {code.description && (
          <p className="ml-7 mt-0.5 truncate text-[11px] text-muted-foreground" title={code.description}>
            {code.description}
          </p>
        )}
      </div>
    </div>
  );
}
