/**
 * Instance Card Component — horizontal row layout
 * Compact, readable, with inline scale controls and action buttons
 */
import React from "react";
import {
  Box, Settings, StopCircle, CheckCircle, XCircle, Clock,
  Network, Activity, GitBranch, Layers, User,
  AlertTriangle, HelpCircle, Minus, Plus, Loader2,
} from "lucide-react";
import type { InstanceResponse } from "@/api";
import { scaleInstance } from "@/api";
import { useToast } from "@/shared";
import { formatApiError } from "@/shared/utils";

interface InstanceCardProps {
  instance: InstanceResponse;
  onModify: (instance: InstanceResponse) => void;
  onTerminate: (instance: InstanceResponse) => void;
  onViewEntries: (instance: InstanceResponse) => void;
  onViewDiagnostics: (instance: InstanceResponse) => void;
  onScale?: (instance: InstanceResponse) => void;
}

type StatusVisual = {
  icon: React.ComponentType<{ className?: string }>;
  color: string;
  bg: string;
  border: string;
  label: string;
};

const STATUS_INFO_MAP: Record<string, StatusVisual> = {
  deployed: {
    icon: CheckCircle,
    color: "text-emerald-500",
    bg: "bg-emerald-50",
    border: "border-emerald-400",
    label: "Deployed",
  },
  failed: {
    icon: XCircle,
    color: "text-rose-500",
    bg: "bg-rose-50",
    border: "border-rose-400",
    label: "Failed",
  },
  "pending-install": {
    icon: Clock,
    color: "text-amber-500",
    bg: "bg-amber-50",
    border: "border-amber-400",
    label: "Pending Install",
  },
  "pending-upgrade": {
    icon: Clock,
    color: "text-amber-500",
    bg: "bg-amber-50",
    border: "border-amber-400",
    label: "Pending Upgrade",
  },
  "pending-rollback": {
    icon: Clock,
    color: "text-amber-500",
    bg: "bg-amber-50",
    border: "border-amber-400",
    label: "Pending Rollback",
  },
  "pending-delete": {
    icon: Clock,
    color: "text-orange-500",
    bg: "bg-orange-50",
    border: "border-orange-400",
    label: "Pending Delete",
  },
  superseded: {
    icon: Layers,
    color: "text-indigo-400",
    bg: "bg-indigo-50",
    border: "border-indigo-300",
    label: "Superseded",
  },
  uninstalled: {
    icon: StopCircle,
    color: "text-slate-500",
    bg: "bg-slate-50",
    border: "border-slate-300",
    label: "Uninstalled",
  },
  unknown: {
    icon: HelpCircle,
    color: "text-slate-400",
    bg: "bg-slate-50",
    border: "border-slate-300",
    label: "Unknown",
  },
};

export const InstanceCard: React.FC<InstanceCardProps> = ({
  instance,
  onModify,
  onTerminate,
  onViewEntries,
  onViewDiagnostics,
  onScale,
}) => {
  const [scaling, setScaling] = React.useState(false);
  const { error: toastError } = useToast();

  const statusKey = instance.status ?? "unknown";
  const statusInfo = STATUS_INFO_MAP[statusKey] ?? STATUS_INFO_MAP["unknown"];
  const StatusIcon = statusInfo.icon;

  const instanceName = instance.name || "Unnamed";
  const chart = instance.chart || instance.repository || "—";
  const version = instance.version || "—";
  const namespace = instance.namespace || "default";
  const revision = instance.revision ?? "—";
  const ownerLabel = ownerDisplayName(instance.ownerUsername, instance.ownerId);

  const currentReplicas: number = instance.replicas ?? 0;

  const statusReason =
    typeof instance.statusReason === "string" && instance.statusReason.trim()
      ? instance.statusReason.trim()
      : null;

  const lastError =
    typeof instance.lastError === "string" && instance.lastError.trim()
      ? instance.lastError.trim()
      : "";

  const canScale = instance.status === "deployed" || instance.status === "failed";

  const handleScale = async (delta: number) => {
    const newReplicas = Math.max(0, currentReplicas + delta);
    if (newReplicas === currentReplicas) return;
    if (!instance.clusterId || !instance.id) return;

    setScaling(true);
    try {
      const result = await scaleInstance(instance.clusterId, instance.id, {
        replicas: newReplicas,
      });
      onScale?.(result.instance ?? { ...instance, replicas: newReplicas });
    } catch (err) {
      toastError(formatApiError(err) || "Scale failed");
    } finally {
      setScaling(false);
    }
  };

  return (
    <div className="hover-lift group relative bg-white border border-slate-200 rounded-lg flex flex-col gap-3 px-4 py-3 transition-all lg:flex-row lg:items-center">
      {/* Left color bar (status) */}
      <div className={`self-stretch w-1 rounded-full flex-shrink-0 ${statusInfo.bg} border ${statusInfo.border}`} />

      {/* Status icon + label */}
      <div className="flex items-center gap-1.5 flex-shrink-0 min-w-[90px]">
        <StatusIcon className={`w-4 h-4 ${statusInfo.color}`} />
        <span className={`text-xs font-semibold ${statusInfo.color}`}>{statusInfo.label}</span>
      </div>

      {/* Name + Chart info */}
      <div className="w-full min-w-0 flex-1 flex items-center gap-4 lg:w-auto">
        <div className="min-w-0">
          <h4 className="text-sm font-semibold text-slate-900 truncate">{instanceName}</h4>
          <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-slate-500 mt-0.5">
            <span className="flex items-center gap-1">
              <Box className="w-3 h-3" />
              <span className="truncate max-w-[200px]">{chart}:{version}</span>
            </span>
            <span className="flex items-center gap-1">
              <Layers className="w-3 h-3" />
              {namespace}
            </span>
            <span className="flex items-center gap-1">
              <GitBranch className="w-3 h-3" />
              rev{revision}
            </span>
            {ownerLabel && (
              <span className="flex min-w-0 items-center gap-1">
                <User className="w-3 h-3" />
                <span className="truncate max-w-[120px]">{ownerLabel}</span>
              </span>
            )}
          </div>
        </div>
      </div>

      {/* Status message or error */}
      {(statusReason || lastError) && (
        <div className="hidden xl:block flex-1 min-w-0 max-w-[280px]">
          {lastError ? (
            <p className="text-xs text-rose-600 truncate flex items-center gap-1">
              <AlertTriangle className="w-3 h-3 flex-shrink-0" />
              {lastError}
            </p>
          ) : statusReason ? (
            <p className="text-xs text-slate-500 truncate">{statusReason}</p>
          ) : null}
        </div>
      )}

      {/* Scale controls */}
      <div className="flex w-full items-center justify-end gap-0.5 flex-shrink-0 lg:w-auto">
        {canScale ? (
          <>
            <button
              onClick={() => handleScale(-1)}
              disabled={scaling || currentReplicas <= 0}
              className="p-1 rounded hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
              title="Scale down"
            >
              {scaling ? (
                <Loader2 className="w-3.5 h-3.5 text-slate-400 animate-spin" />
              ) : (
                <Minus className="w-3.5 h-3.5 text-slate-500" />
              )}
            </button>
            <span className="w-8 text-center text-sm font-bold text-slate-700 tabular-nums">
              {currentReplicas}
            </span>
            <button
              onClick={() => handleScale(1)}
              disabled={scaling}
              className="p-1 rounded hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
              title="Scale up"
            >
              <Plus className="w-3.5 h-3.5 text-slate-500" />
            </button>
          </>
        ) : (
          <span className="text-xs text-slate-400 w-16 text-center">{currentReplicas} repl.</span>
        )}
      </div>

      {/* Action buttons */}
      <div className="flex w-full flex-wrap items-center justify-end gap-1.5 flex-shrink-0 lg:w-auto">
        <button
          onClick={() => onViewEntries(instance)}
          className="flex items-center gap-1 px-2 py-1.5 rounded-md text-slate-500 hover:text-blue-600 hover:bg-blue-50 transition-colors text-xs font-medium"
          title="Entries"
        >
          <Network className="w-3.5 h-3.5" />
          <span className="hidden sm:inline">Entries</span>
        </button>
        <button
          onClick={() => onViewDiagnostics(instance)}
          className="flex items-center gap-1 px-2 py-1.5 rounded-md text-slate-500 hover:text-amber-600 hover:bg-amber-50 transition-colors text-xs font-medium"
          title="Diagnostics"
        >
          <Activity className="w-3.5 h-3.5" />
          <span className="hidden sm:inline">Diag</span>
        </button>
        <button
          onClick={() => onModify(instance)}
          className="flex items-center gap-1 px-2 py-1.5 rounded-md text-slate-500 hover:text-indigo-600 hover:bg-indigo-50 transition-colors text-xs font-medium"
          title="Modify"
        >
          <Settings className="w-3.5 h-3.5" />
          <span className="hidden sm:inline">Modify</span>
        </button>
        <button
          onClick={() => onTerminate(instance)}
          className="flex items-center gap-1 px-2 py-1.5 rounded-md text-slate-500 hover:text-rose-600 hover:bg-rose-50 transition-colors text-xs font-medium"
          title="Delete"
        >
          <StopCircle className="w-3.5 h-3.5" />
          <span className="hidden sm:inline">Delete</span>
        </button>
      </div>
    </div>
  );
};

const ownerDisplayName = (ownerUsername?: string, ownerId?: string): string => {
  const username = ownerUsername?.trim();
  if (username) return username;
  const id = ownerId?.trim();
  if (!id) return "";
  if (id.length <= 12) return id;
  return `${id.slice(0, 8)}...${id.slice(-4)}`;
};
