"use client";

import { Pencil } from "lucide-react";
import type { AppEntry } from "@/lib/types";
import { LUCIDE_ICONS } from "./lucideIcons";

interface AppTileProps {
  app: AppEntry;
  categoryName?: string;
  onEdit: (app: AppEntry) => void;
}

function AppIconDisplay({ icon, size = 32 }: { icon: AppEntry["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 AppTile({ app, categoryName, onEdit }: AppTileProps) {
  return (
    <a
      href={app.url}
      target="_blank"
      rel="noopener noreferrer"
      title={app.description || app.name}
      className="group relative flex flex-col items-center gap-2 rounded-xl border border-zinc-200 bg-white p-4 shadow-sm 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: app.color }}
      />

      {/* Edit button */}
      <button
        onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();
          onEdit(app);
        }}
        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} />
      </button>

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

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

      {/* Category badge */}
      {categoryName && (
        <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">
          {categoryName}
        </span>
      )}
    </a>
  );
}

export { AppIconDisplay };
