/**
 * Tag Card Component
 * Card for displaying a single chart tag/artifact with Launch action
 */
import React, { useState } from "react";
import { Box, Copy, File, HardDrive, Package, Rocket } from "lucide-react";
import { LaunchModal } from "./LaunchModal";
import { useToast } from "@/shared";
import type { ArtifactListItem } from "@/api";
import { inferArtifactCategory, type ArtifactCategory } from "../utils/artifactType";

interface TagCardProps {
  registryId: string;
  registryUrl?: string;
  tag: ArtifactListItem;
  isLatest?: boolean;
}

export const TagCard: React.FC<TagCardProps> = ({ registryId, registryUrl, tag, isLatest = false }) => {
  const { success } = useToast();
  const [launchModalOpen, setLaunchModalOpen] = useState(false);
  const category = inferArtifactCategory(tag);

  const handleLaunch = () => {
    if (category !== "chart") return;
    setLaunchModalOpen(true);
  };

  const handleCopy = () => {
    const tagName = tag.tag || '';
    if (!tagName || !tag.repositoryName) return;
    const registryHost = normalizeRegistryHost(registryUrl);
    const repositoryPath = registryHost
      ? `${registryHost}/${tag.repositoryName}`
      : tag.repositoryName;
    const pullCommand = `helm pull oci://${repositoryPath} --version ${tagName}`;
    navigator.clipboard.writeText(pullCommand);
    success("Pull command copied to clipboard!");
  };

  const formatSize = (bytes: number) => {
    if (bytes === 0) return "N/A";
    const mb = bytes / (1024 * 1024);
    if (mb < 1) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${mb.toFixed(1)} MB`;
  };

  const getTypeColor = (type: ArtifactCategory) => {
    switch (type) {
      case "chart":
        return "text-blue-500 bg-blue-500/10 border-blue-500/30";
      case "image":
        return "text-green-500 bg-green-500/10 border-green-500/30";
      default:
        return "text-slate-500 bg-gray-500/10 border-gray-500/30";
    }
  };

  const getTypeIcon = (type: ArtifactCategory) => {
    const className = "w-4 h-4";
    switch (type) {
      case "chart": return <Package className={className} />;
      case "image": return <Box className={className} />;
      default: return <File className={className} />;
    }
  };

  return (
    <>
      <div className="hover-lift relative bg-white border border-slate-200 rounded-lg p-4 min-w-[180px] hover:border-brand-blue/50 transition-all group">
        {/* LATEST badge */}
        {isLatest && (
          <span className="absolute -top-2 right-2 px-2 py-0.5 rounded-full text-[11px] font-bold uppercase tracking-wider bg-emerald-500 text-white shadow-sm z-10">
            LATEST
          </span>
        )}

        {/* Tag name + type */}
        <div className="flex items-center gap-2 mb-2">
          <div className={`w-7 h-7 rounded-md border ${getTypeColor(category)} flex items-center justify-center flex-shrink-0`}>
            {getTypeIcon(category)}
          </div>
          <h3 className="text-sm font-semibold text-slate-900 truncate flex-1" title={tag.tag}>
            {tag.tag || 'N/A'}
          </h3>
          <span className={`px-1.5 py-0.5 rounded text-[11px] border ${getTypeColor(category)} flex-shrink-0`}>
            {category}
          </span>
        </div>

        {/* Repository path */}
        <p className="text-xs text-slate-400 truncate mb-3" title={tag.repositoryName || ''}>
          {tag.repositoryName || ' '}
        </p>

        {/* Actions row */}
        <div className="flex items-center justify-between gap-2">
          <div className="flex items-center gap-1.5 text-xs text-slate-400 flex-shrink-0">
            <HardDrive className="w-3.5 h-3.5" />
            <span>{formatSize(tag.size || 0)}</span>
          </div>
          <div className="flex items-center gap-2 flex-shrink-0">
            <button
              onClick={handleCopy}
              className="px-2.5 py-1.5 bg-white hover:bg-slate-50 text-slate-500 border border-slate-200 rounded text-xs transition-colors flex items-center gap-1"
              title="Copy pull command"
            >
              <Copy className="w-3.5 h-3.5" />
              <span>Copy</span>
            </button>
            {category === "chart" && (
              <button
                onClick={handleLaunch}
                className="px-2.5 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded text-xs font-medium transition-colors flex items-center gap-1"
                title="Launch this Helm chart"
              >
                <Rocket className="w-3.5 h-3.5" />
                <span>Launch</span>
              </button>
            )}
          </div>
        </div>
      </div>

      {launchModalOpen && tag.repositoryName && tag.tag && (
        <LaunchModal
          isOpen={launchModalOpen}
          onClose={() => setLaunchModalOpen(false)}
          registryId={registryId}
          repositoryName={tag.repositoryName}
          tag={tag.tag}
          artifactType={category}
        />
      )}
    </>
  );
};

const normalizeRegistryHost = (url?: string) => {
  if (!url) return "";
  try { return new URL(url).host; }
  catch { return url.replace(/^https?:\/\//, "").replace(/\/+$/, ""); }
};
