"use client";

import React from "react";
import { Button } from "@/components/ui/button";
import { Edit, Trash2 } from "lucide-react";
import { cn } from "@/lib/utils";
import { useUpdateCategory } from "@/hooks/queries/useCategories";
import type { CategoryInfo } from "@/types/commonCode";

interface CategoryItemProps {
  category: CategoryInfo;
  isSelected: boolean;
  onSelect: () => void;
  onEdit: () => void;
  onDelete: () => void;
}

export function CategoryItem({ category, isSelected, onSelect, onEdit, onDelete }: CategoryItemProps) {
  const updateCategoryMutation = useUpdateCategory();
  const isActive = category.is_active === "Y";

  const handleToggleActive = async (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (updateCategoryMutation.isPending) return;
    try {
      await updateCategoryMutation.mutateAsync({
        categoryCode: category.category_code,
        data: {
          categoryName: category.category_name,
          categoryNameEng: category.category_name_eng || "",
          description: category.description || "",
          sortOrder: category.sort_order,
          isActive: isActive ? "N" : "Y",
        },
      });
    } catch (error) {
      console.error("카테고리 활성 상태 변경 실패:", error);
    }
  };

  return (
    <div
      onClick={onSelect}
      className={cn(
        "group flex cursor-pointer items-center justify-between rounded-md border px-2.5 py-2 transition-colors",
        isSelected
          ? "border-primary/60 bg-primary/5"
          : "border-border bg-card hover:border-primary/30 hover:bg-muted/40",
      )}
    >
      <div className="min-w-0 flex-1">
        <div className="flex items-center gap-1.5">
          {/* 활성 상태 점 (클릭으로 토글) */}
          <button
            type="button"
            onClick={handleToggleActive}
            onPointerDown={(e) => e.stopPropagation()}
            onMouseDown={(e) => e.stopPropagation()}
            title={isActive ? "활성 (클릭하여 비활성)" : "비활성 (클릭하여 활성)"}
            className={cn(
              "h-1.5 w-1.5 flex-shrink-0 rounded-full transition-colors",
              isActive ? "bg-emerald-500" : "bg-muted-foreground/40",
              updateCategoryMutation.isPending && "opacity-50",
            )}
          />
          <span className="truncate text-[13px] font-medium" title={category.category_name}>
            {category.category_name}
          </span>
        </div>
        <p className="mt-0.5 font-mono text-[10px] text-muted-foreground">{category.category_code}</p>
      </div>

      {/* 액션 — 선택되었거나 hover 시 노출 */}
      <div
        className={cn(
          "flex items-center gap-0.5 transition-opacity",
          isSelected ? "opacity-100" : "opacity-0 group-hover:opacity-100",
        )}
        onClick={(e) => e.stopPropagation()}
      >
        <Button variant="ghost" size="icon" className="h-6 w-6" onClick={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={onDelete} title="삭제">
          <Trash2 className="h-3 w-3" />
        </Button>
      </div>
    </div>
  );
}
