"use client";

import { useState } from "react";
import { ChevronDown, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { getImportanceColors } from "@/lib/tech-colors";

interface ImportanceBadgeProps {
  importance: string;
  onImportanceChange: (newImportance: string) => void;
  disabled?: boolean;
}

export function ImportanceBadge({
  importance,
  onImportanceChange,
  disabled = false,
}: ImportanceBadgeProps) {
  const [isOpen, setIsOpen] = useState(false);
  const colors = getImportanceColors(importance);

  const handleImportanceChange = (newImportance: string) => {
    onImportanceChange(newImportance);
    setIsOpen(false);
  };

  const IMPORTANCE_LABELS = {
    incontournable: "Incontournable",
    majeure: "Majeure",
    standard: "Standard",
  };

  return (
    <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
      <DropdownMenuTrigger asChild>
        <Button
          variant="outline"
          size="sm"
          className={`h-6 px-2 text-xs font-medium border ${colors.bg} ${
            colors.text
          } ${colors.border} hover:opacity-80 transition-all ${
            disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer"
          }`}
          disabled={disabled}
        >
          <span
            className={`w-2 h-2 rounded-full ${colors.text.replace(
              "text-",
              "bg-"
            )}`}
          />
          {IMPORTANCE_LABELS[importance as keyof typeof IMPORTANCE_LABELS] ||
            importance}
          {!disabled && <ChevronDown className="w-3 h-3 ml-1" />}
        </Button>
      </DropdownMenuTrigger>

      {!disabled && (
        <DropdownMenuContent align="end" className="w-40">
          {Object.entries(IMPORTANCE_LABELS).map(([key, label]) => {
            const itemColors = getImportanceColors(key);
            return (
              <DropdownMenuItem
                key={key}
                onClick={() => handleImportanceChange(key)}
                className="flex items-center gap-2"
              >
                <span
                  className={`w-2 h-2 rounded-full ${itemColors.text.replace(
                    "text-",
                    "bg-"
                  )}`}
                />
                {label}
                {importance === key && <Check className="w-3 h-3 ml-auto" />}
              </DropdownMenuItem>
            );
          })}
        </DropdownMenuContent>
      )}
    </DropdownMenu>
  );
}
