"use client";

import { Pencil } from "lucide-react";
import type { ToolEntry } from "@/lib/types";
import { LUCIDE_ICONS } from "@/components/apps/lucideIcons";

interface ToolTileProps {
  tool: ToolEntry;
  onEdit: (tool: ToolEntry) => void;
}

function ToolIconDisplay({ icon, size = 32 }: { icon: ToolEntry["icon"]; size?: number }) {
  if (icon.type === "lucide") {
    const IconComponent = LUCIDE_ICONS[icon.value] ?? LUCIDE_ICONS.Box;
    return <IconComponent size={size} />;
  }
  if (icon.type === "emoji") {
    return <span style={{ fontSize: size }}>{icon.value}</span>;
  }
  if (icon.type === "upload") {
    return <img src={icon.value} alt="" width={size} height={size} className="rounded" />;
  }
  return null;
}

export function ToolTile({ tool, onEdit }: ToolTileProps) {
  return (
    <button
      onClick={() => onEdit(tool)}
      title={tool.description || tool.name}
      className="group relative flex w-full flex-col items-center gap-2 rounded-xl border border-zinc-200 bg-white p-4 shadow-sm text-left transition-shadow hover:shadow-md dark:border-zinc-800 dark:bg-zinc-900"
    >
      {/* Colored accent bar */}
      <div
        className="absolute inset-x-0 top-0 h-1 rounded-t-xl"
        style={{ backgroundColor: tool.color }}
      />

      {/* Edit button */}
      <div
        className="absolute right-2 top-2 rounded-md p-1 text-zinc-400 opacity-0 transition-opacity hover:bg-zinc-100 hover:text-zinc-600 group-hover:opacity-100 dark:hover:bg-zinc-800 dark:hover:text-zinc-300"
      >
        <Pencil size={14} />
      </div>

      {/* Status indicator */}
      <div className="absolute left-2 top-2">
        <div
          className={`h-2.5 w-2.5 rounded-full ${
            tool.status === "online"
              ? "bg-emerald-500"
              : "bg-zinc-300 dark:bg-zinc-600"
          }`}
          title={tool.status}
        />
      </div>

      {/* Icon */}
      <div className="mt-2 flex items-center justify-center text-zinc-700 dark:text-zinc-300">
        <ToolIconDisplay icon={tool.icon} />
      </div>

      {/* Name */}
      <span className="text-center text-sm font-medium text-zinc-900 dark:text-zinc-100">
        {tool.name}
      </span>

      {/* Address */}
      {tool.address && (
        <span className="rounded-full bg-zinc-100 px-2 py-0.5 text-xs text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400">
          {tool.address}
        </span>
      )}
    </button>
  );
}
