"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(
        "group cursor-pointer rounded-lg border p-3 transition-all hover:shadow-sm",
        isSelected ? "border-gray-300 bg-gray-100" : "border-gray-200 bg-white hover:bg-gray-50",
      )}
      onClick={onSelect}
    >
      <div className="flex items-start justify-between">
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2">
            <h3 className="font-medium text-gray-900">{category.category_name}</h3>
            <Badge
              variant={category.is_active === "Y" ? "default" : "secondary"}
              className={cn(
                "cursor-pointer transition-colors",
                category.is_active === "Y"
                  ? "bg-green-100 text-green-800 hover:bg-green-200 hover:text-green-900"
                  : "bg-gray-100 text-gray-600 hover:bg-gray-200 hover:text-gray-700",
                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="mt-1 text-sm text-gray-600">{category.category_code}</p>
          {category.description && <p className="mt-1 text-sm text-gray-500">{category.description}</p>}
        </div>

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