"use client";

import React from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
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 handleToggleActive = async (checked: boolean) => {
    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: checked ? "Y" : "N",
        },
      });
    } catch (error) {
      console.error("카테고리 활성 상태 변경 실패:", error);
    }
  };

  return (
    <div
      className={cn(
        "bg-card cursor-pointer rounded-lg border p-4 shadow-sm transition-all",
        isSelected ? "shadow-md" : "hover:shadow-md",
      )}
      onClick={onSelect}
    >
      <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">{category.category_name}</h4>
            <Badge
              variant={category.is_active === "Y" ? "default" : "secondary"}
              className={cn(
                "cursor-pointer text-xs transition-colors",
                updateCategoryMutation.isPending && "cursor-not-allowed opacity-50",
              )}
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                if (!updateCategoryMutation.isPending) {
                  handleToggleActive(category.is_active !== "Y");
                }
              }}
              onPointerDown={(e) => e.stopPropagation()}
              onMouseDown={(e) => e.stopPropagation()}
            >
              {category.is_active === "Y" ? "활성" : "비활성"}
            </Badge>
          </div>
          <p className="text-muted-foreground mt-1 text-xs">{category.category_code}</p>
          {category.description && <p className="text-muted-foreground mt-1 text-xs">{category.description}</p>}
        </div>

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