'use client';

import { useState, useCallback } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useRouter, useParams } from 'next/navigation';
import { useTranslation } from 'react-i18next';
import { apiClient } from '@/infrastructure/api/api-client';
import { queryKeys } from '@/infrastructure/api/query-keys';
import { cn } from '@/lib/utils';

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

interface Runbook {
  id: string;
  name: string;
  description: string;
  triggerType: 'manual' | 'alert' | 'scheduled';
  promptTemplate: string;
  allowedTools: string[];
  maxRiskLevel: number;
  autoApprove: boolean;
  enabled: boolean;
  createdAt: string;
  updatedAt: string;
}

interface RunbookExecution {
  id: string;
  runbookId: string;
  status: 'running' | 'completed' | 'failed';
  triggeredBy: string;
  startedAt: string;
  endedAt?: string;
  durationMs?: number;
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const AVAILABLE_TOOLS = [
  'Bash',
  'Read',
  'Write',
  'Glob',
  'Grep',
  'Edit',
  'ssh',
  'kubectl',
  'docker',
  'systemctl',
  'curl',
  'ping',
];

const RISK_LEVEL_STYLES: Record<number, string> = {
  0: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
  1: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
  2: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
  3: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
};

const TRIGGER_STYLES: Record<string, string> = {
  manual: 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300',
  alert: 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-400',
  scheduled: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400',
};

const EXECUTION_STATUS_STYLES: Record<string, string> = {
  running: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
  completed: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
  failed: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
};

// ---------------------------------------------------------------------------
// Badge helpers
// ---------------------------------------------------------------------------

function RiskBadge({ level }: { level: number }) {
  const { t } = useTranslation('runbooks');
  return (
    <span
      className={cn(
        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium',
        RISK_LEVEL_STYLES[level] ?? RISK_LEVEL_STYLES[0],
      )}
    >
      {t(`riskLevels.${level}`) ?? `L${level}`}
    </span>
  );
}

function TriggerBadge({ type }: { type: string }) {
  return (
    <span
      className={cn(
        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium capitalize',
        TRIGGER_STYLES[type] ?? TRIGGER_STYLES.manual,
      )}
    >
      {type}
    </span>
  );
}

function StatusBadge({ status }: { status: string }) {
  return (
    <span
      className={cn(
        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium capitalize',
        EXECUTION_STATUS_STYLES[status] ?? EXECUTION_STATUS_STYLES.running,
      )}
    >
      {status}
    </span>
  );
}

// ---------------------------------------------------------------------------
// Toggle switch
// ---------------------------------------------------------------------------

function ToggleSwitch({
  checked,
  disabled,
  onChange,
  label,
}: {
  checked: boolean;
  disabled?: boolean;
  onChange: (value: boolean) => void;
  label: string;
}) {
  return (
    <button
      type="button"
      onClick={() => onChange(!checked)}
      disabled={disabled}
      className="flex items-center gap-2"
      title={label}
    >
      <span
        className={cn(
          'relative inline-flex h-5 w-9 items-center rounded-full transition-colors',
          checked ? 'bg-primary' : 'bg-muted',
          disabled && 'opacity-50 cursor-not-allowed',
        )}
      >
        <span
          className={cn(
            'inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform',
            checked ? 'translate-x-[18px]' : 'translate-x-[3px]',
          )}
        />
      </span>
      <span className="text-sm">{label}</span>
    </button>
  );
}

// ---------------------------------------------------------------------------
// Delete confirmation dialog
// ---------------------------------------------------------------------------

function DeleteDialog({
  open,
  name,
  deleting,
  onClose,
  onConfirm,
}: {
  open: boolean;
  name: string;
  deleting: boolean;
  onClose: () => void;
  onConfirm: () => void;
}) {
  const { t } = useTranslation('runbooks');
  const { t: tc } = useTranslation('common');

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative z-10 w-full max-w-sm bg-card border rounded-lg shadow-lg p-6 mx-4">
        <h2 className="text-lg font-semibold mb-2">{t('deleteDialog.title')}</h2>
        <p className="text-sm text-muted-foreground mb-6">
          {t('deleteDialog.message')}
        </p>
        <div className="flex justify-end gap-3">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm rounded-md border border-input hover:bg-accent"
            disabled={deleting}
          >
            {tc('cancel')}
          </button>
          <button
            onClick={onConfirm}
            disabled={deleting}
            className="px-4 py-2 text-sm rounded-md bg-destructive text-destructive-foreground hover:bg-destructive/90 disabled:opacity-50"
          >
            {deleting ? tc('deleting') : tc('delete')}
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Helper: format date
// ---------------------------------------------------------------------------

function formatDate(dateStr: string): string {
  try {
    return new Date(dateStr).toLocaleString();
  } catch {
    return dateStr;
  }
}

function formatDuration(ms?: number): string {
  if (ms == null) return '--';
  if (ms < 1000) return `${ms}ms`;
  const seconds = Math.round(ms / 1000);
  if (seconds < 60) return `${seconds}s`;
  const minutes = Math.floor(seconds / 60);
  const remaining = seconds % 60;
  return `${minutes}m ${remaining}s`;
}

// ---------------------------------------------------------------------------
// Main page component
// ---------------------------------------------------------------------------

export default function RunbookDetailPage() {
  const { t } = useTranslation('runbooks');
  const { t: tc } = useTranslation('common');
  const router = useRouter();
  const params = useParams();
  const id = params.id as string;
  const queryClient = useQueryClient();

  // State ------------------------------------------------------------------
  const [isEditingPrompt, setIsEditingPrompt] = useState(false);
  const [promptDraft, setPromptDraft] = useState('');
  const [toolsDraft, setToolsDraft] = useState<string[]>([]);
  const [isEditingTools, setIsEditingTools] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  // Queries ----------------------------------------------------------------
  const {
    data: runbook,
    isLoading,
    error,
  } = useQuery<Runbook>({
    queryKey: queryKeys.runbooks.detail(id),
    queryFn: () => apiClient<Runbook>(`/api/v1/ops/runbooks/${id}`),
    enabled: !!id,
  });

  const { data: executionsData } = useQuery<RunbookExecution[]>({
    queryKey: [...queryKeys.runbooks.detail(id), 'executions'],
    queryFn: () =>
      apiClient<RunbookExecution[]>(
        `/api/v1/ops/runbooks/${id}/executions`,
      ),
    enabled: !!id,
  });

  const executions = Array.isArray(executionsData) ? executionsData : [];

  // Mutations --------------------------------------------------------------
  const updateMutation = useMutation({
    mutationFn: (body: Partial<Runbook>) =>
      apiClient<Runbook>(`/api/v1/ops/runbooks/${id}`, {
        method: 'PUT',
        body,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.runbooks.detail(id) });
      queryClient.invalidateQueries({ queryKey: queryKeys.runbooks.all });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: () =>
      apiClient<void>(`/api/v1/ops/runbooks/${id}`, { method: 'DELETE' }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.runbooks.all });
      router.push('/runbooks');
    },
  });

  const executeMutation = useMutation({
    mutationFn: () =>
      apiClient<void>(`/api/v1/ops/runbooks/${id}/execute`, {
        method: 'POST',
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [...queryKeys.runbooks.detail(id), 'executions'],
      });
    },
  });

  const duplicateMutation = useMutation({
    mutationFn: () => {
      if (!runbook) throw new Error('Runbook not loaded');
      return apiClient<Runbook>('/api/v1/ops/runbooks', {
        method: 'POST',
        body: {
          name: `${runbook.name} (Copy)`,
          description: runbook.description,
          triggerType: runbook.triggerType,
          promptTemplate: runbook.promptTemplate,
          allowedTools: runbook.allowedTools,
          maxRiskLevel: runbook.maxRiskLevel,
          autoApprove: runbook.autoApprove,
          enabled: false,
        },
      });
    },
    onSuccess: (newRunbook) => {
      queryClient.invalidateQueries({ queryKey: queryKeys.runbooks.all });
      router.push(`/runbooks/${newRunbook.id}`);
    },
  });

  // Handlers ---------------------------------------------------------------
  const handleStartEditPrompt = useCallback(() => {
    if (!runbook) return;
    setPromptDraft(runbook.promptTemplate);
    setIsEditingPrompt(true);
  }, [runbook]);

  const handleSavePrompt = useCallback(() => {
    updateMutation.mutate(
      { promptTemplate: promptDraft },
      {
        onSuccess: () => {
          setIsEditingPrompt(false);
        },
      },
    );
  }, [promptDraft, updateMutation]);

  const handleCancelEditPrompt = useCallback(() => {
    setIsEditingPrompt(false);
    setPromptDraft('');
  }, []);

  const handleStartEditTools = useCallback(() => {
    if (!runbook) return;
    setToolsDraft([...runbook.allowedTools]);
    setIsEditingTools(true);
  }, [runbook]);

  const handleToggleTool = useCallback((tool: string) => {
    setToolsDraft((prev) =>
      prev.includes(tool) ? prev.filter((item) => item !== tool) : [...prev, tool],
    );
  }, []);

  const handleSaveTools = useCallback(() => {
    updateMutation.mutate(
      { allowedTools: toolsDraft },
      {
        onSuccess: () => {
          setIsEditingTools(false);
        },
      },
    );
  }, [toolsDraft, updateMutation]);

  const handleCancelEditTools = useCallback(() => {
    setIsEditingTools(false);
    setToolsDraft([]);
  }, []);

  const handleToggleAutoApprove = useCallback(
    (value: boolean) => {
      updateMutation.mutate({ autoApprove: value });
    },
    [updateMutation],
  );

  const handleToggleEnabled = useCallback(
    (value: boolean) => {
      updateMutation.mutate({ enabled: value });
    },
    [updateMutation],
  );

  // Render: Loading --------------------------------------------------------
  if (isLoading) {
    return (
      <div className="text-sm text-muted-foreground py-12 text-center">
        {t('detail.loading')}
      </div>
    );
  }

  // Render: Error ----------------------------------------------------------
  if (error) {
    return (
      <div>
        <button
          onClick={() => router.push('/runbooks')}
          className="text-sm text-muted-foreground hover:text-foreground mb-4 inline-flex items-center gap-1"
        >
          &larr; {t('detail.backToRunbooks')}
        </button>
        <div className="p-4 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
          {t('detail.loadError')} {(error as Error).message}
        </div>
      </div>
    );
  }

  // Render: Not found ------------------------------------------------------
  if (!runbook) {
    return (
      <div>
        <button
          onClick={() => router.push('/runbooks')}
          className="text-sm text-muted-foreground hover:text-foreground mb-4 inline-flex items-center gap-1"
        >
          &larr; {t('detail.backToRunbooks')}
        </button>
        <div className="text-sm text-muted-foreground py-12 text-center">
          {t('detail.notFound')}
        </div>
      </div>
    );
  }

  // Render: Main -----------------------------------------------------------
  return (
    <div>
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div className="flex items-center gap-3">
          <button
            onClick={() => router.push('/runbooks')}
            className="text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1"
          >
            &larr; {t('detail.back')}
          </button>
          <div className="h-6 w-px bg-border" />
          <div>
            <h1 className="text-2xl font-bold">{runbook.name}</h1>
            <p className="text-sm text-muted-foreground mt-0.5">
              {runbook.description || t('detail.noDescription')}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <TriggerBadge type={runbook.triggerType} />
          <RiskBadge level={runbook.maxRiskLevel} />
          <span
            className={cn(
              'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium',
              runbook.enabled
                ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                : 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300',
            )}
          >
            {runbook.enabled ? tc('enabled') : tc('disabled')}
          </span>
        </div>
      </div>

      {/* Mutation error banner */}
      {(updateMutation.error || executeMutation.error || duplicateMutation.error) && (
        <div className="p-4 mb-4 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
          {(
            (updateMutation.error ||
              executeMutation.error ||
              duplicateMutation.error) as Error
          ).message}
        </div>
      )}

      {/* Two-column layout */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left column */}
        <div className="lg:col-span-2 space-y-6">
          {/* Overview card */}
          <div className="border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('detail.overview')}</h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  {t('form.name')}
                </label>
                <p className="text-sm mt-1">{runbook.name}</p>
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  {t('detail.triggerType')}
                </label>
                <p className="mt-1">
                  <TriggerBadge type={runbook.triggerType} />
                </p>
              </div>
              <div className="sm:col-span-2">
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  {tc('description')}
                </label>
                <p className="text-sm mt-1 text-muted-foreground">
                  {runbook.description || t('detail.noDescription')}
                </p>
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  {tc('created')}
                </label>
                <p className="text-sm mt-1 text-muted-foreground">
                  {formatDate(runbook.createdAt)}
                </p>
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  {tc('updated')}
                </label>
                <p className="text-sm mt-1 text-muted-foreground">
                  {formatDate(runbook.updatedAt)}
                </p>
              </div>
            </div>
          </div>

          {/* Prompt Template section */}
          <div className="border rounded-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold">{t('detail.promptTemplate')}</h2>
              <div className="flex items-center gap-2">
                {isEditingPrompt ? (
                  <>
                    <button
                      onClick={handleCancelEditPrompt}
                      className="px-3 py-1.5 text-xs rounded-md border border-input hover:bg-accent transition-colors"
                    >
                      {tc('cancel')}
                    </button>
                    <button
                      onClick={handleSavePrompt}
                      disabled={updateMutation.isPending}
                      className="px-3 py-1.5 text-xs rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors"
                    >
                      {updateMutation.isPending ? tc('saving') : tc('save')}
                    </button>
                  </>
                ) : (
                  <button
                    onClick={handleStartEditPrompt}
                    className="px-3 py-1.5 text-xs rounded-md border border-input hover:bg-accent transition-colors"
                  >
                    {tc('edit')}
                  </button>
                )}
              </div>
            </div>

            {isEditingPrompt ? (
              <textarea
                value={promptDraft}
                onChange={(e) => setPromptDraft(e.target.value)}
                className="w-full bg-gray-950 text-green-400 font-mono text-sm p-4 rounded-md min-h-[300px] resize-y border-0 focus:outline-none focus:ring-2 focus:ring-ring"
                spellCheck={false}
              />
            ) : (
              <div className="bg-gray-950 text-gray-200 font-mono text-sm p-4 rounded-md whitespace-pre-wrap min-h-[300px]">
                {runbook.promptTemplate || t('detail.noPrompt')}
              </div>
            )}
          </div>

          {/* Allowed Tools section */}
          <div className="border rounded-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold">{t('detail.allowedTools')}</h2>
              <div className="flex items-center gap-2">
                {isEditingTools ? (
                  <>
                    <button
                      onClick={handleCancelEditTools}
                      className="px-3 py-1.5 text-xs rounded-md border border-input hover:bg-accent transition-colors"
                    >
                      {tc('cancel')}
                    </button>
                    <button
                      onClick={handleSaveTools}
                      disabled={updateMutation.isPending}
                      className="px-3 py-1.5 text-xs rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors"
                    >
                      {updateMutation.isPending ? tc('saving') : tc('save')}
                    </button>
                  </>
                ) : (
                  <button
                    onClick={handleStartEditTools}
                    className="px-3 py-1.5 text-xs rounded-md border border-input hover:bg-accent transition-colors"
                  >
                    {tc('edit')}
                  </button>
                )}
              </div>
            </div>

            {isEditingTools ? (
              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
                {AVAILABLE_TOOLS.map((tool) => (
                  <label
                    key={tool}
                    className="flex items-center gap-2 text-sm cursor-pointer"
                  >
                    <input
                      type="checkbox"
                      checked={toolsDraft.includes(tool)}
                      onChange={() => handleToggleTool(tool)}
                      className="accent-primary h-4 w-4"
                    />
                    <span className="font-mono text-xs">{tool}</span>
                  </label>
                ))}
              </div>
            ) : (
              <div className="flex flex-wrap gap-2">
                {runbook.allowedTools.length === 0 ? (
                  <p className="text-sm text-muted-foreground">
                    {t('detail.noTools')}
                  </p>
                ) : (
                  runbook.allowedTools.map((tool) => (
                    <span
                      key={tool}
                      className="inline-flex items-center px-2.5 py-1 rounded-md bg-muted text-xs font-mono"
                    >
                      {tool}
                    </span>
                  ))
                )}
              </div>
            )}
          </div>

          {/* Execution History */}
          <div className="border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('detail.executionHistory')}</h2>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b bg-muted/50">
                    <th className="text-left px-4 py-3 font-medium">{t('detail.executionTable.date')}</th>
                    <th className="text-left px-4 py-3 font-medium">{t('detail.executionTable.status')}</th>
                    <th className="text-left px-4 py-3 font-medium">
                      {t('detail.executionTable.duration')}
                    </th>
                    <th className="text-left px-4 py-3 font-medium">
                      {t('detail.executionTable.triggeredBy')}
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {executions.length === 0 ? (
                    <tr>
                      <td
                        colSpan={4}
                        className="text-center text-muted-foreground py-12"
                      >
                        {t('detail.noExecutions')}
                      </td>
                    </tr>
                  ) : (
                    executions.map((exec) => (
                      <tr
                        key={exec.id}
                        className="border-b last:border-b-0 hover:bg-muted/30 transition-colors"
                      >
                        <td className="px-4 py-3 text-muted-foreground">
                          {formatDate(exec.startedAt)}
                        </td>
                        <td className="px-4 py-3">
                          <StatusBadge status={exec.status} />
                        </td>
                        <td className="px-4 py-3 font-mono text-xs">
                          {formatDuration(exec.durationMs)}
                        </td>
                        <td className="px-4 py-3 text-muted-foreground">
                          {exec.triggeredBy}
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>

        {/* Right column */}
        <div className="lg:col-span-1 space-y-6">
          {/* Configuration card */}
          <div className="border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('detail.configuration')}</h2>
            <div className="space-y-5">
              {/* Trigger type */}
              <div>
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  {t('detail.triggerType')}
                </label>
                <p className="mt-1.5">
                  <TriggerBadge type={runbook.triggerType} />
                </p>
              </div>

              {/* Max Risk Level */}
              <div>
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  {t('detail.maxRiskLevel')}
                </label>
                <p className="mt-1.5">
                  <RiskBadge level={runbook.maxRiskLevel} />
                </p>
              </div>

              {/* Auto-Approve toggle */}
              <div>
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide block mb-1.5">
                  {t('detail.autoApprove')}
                </label>
                <ToggleSwitch
                  checked={runbook.autoApprove}
                  disabled={updateMutation.isPending}
                  onChange={handleToggleAutoApprove}
                  label={runbook.autoApprove ? tc('enabled') : tc('disabled')}
                />
                <p className="text-xs text-muted-foreground mt-1">
                  {t('detail.autoApproveDescription')}
                </p>
              </div>

              {/* Enabled toggle */}
              <div>
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide block mb-1.5">
                  {t('detail.statusLabel')}
                </label>
                <ToggleSwitch
                  checked={runbook.enabled}
                  disabled={updateMutation.isPending}
                  onChange={handleToggleEnabled}
                  label={runbook.enabled ? tc('enabled') : tc('disabled')}
                />
              </div>
            </div>
          </div>

          {/* Quick Actions card */}
          <div className="border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('detail.quickActions')}</h2>
            <div className="space-y-3">
              {/* Execute Now */}
              <button
                onClick={() => executeMutation.mutate()}
                disabled={executeMutation.isPending || !runbook.enabled}
                className={cn(
                  'w-full px-4 py-2 text-sm rounded-md font-medium transition-colors disabled:opacity-50',
                  'bg-primary text-primary-foreground hover:bg-primary/90',
                )}
              >
                {executeMutation.isPending ? t('detail.executing') : t('detail.executeNow')}
              </button>
              {!runbook.enabled && (
                <p className="text-xs text-muted-foreground">
                  {t('detail.enableToExecute')}
                </p>
              )}

              {/* Duplicate */}
              <button
                onClick={() => duplicateMutation.mutate()}
                disabled={duplicateMutation.isPending}
                className="w-full px-4 py-2 text-sm rounded-md border border-input hover:bg-accent font-medium transition-colors disabled:opacity-50"
              >
                {duplicateMutation.isPending ? t('detail.duplicating') : t('detail.duplicate')}
              </button>

              {/* Delete */}
              <button
                onClick={() => setShowDeleteDialog(true)}
                disabled={deleteMutation.isPending}
                className="w-full px-4 py-2 text-sm rounded-md border border-destructive/50 text-destructive hover:bg-destructive/10 font-medium transition-colors disabled:opacity-50"
              >
                {t('detail.deleteRunbook')}
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Delete confirmation dialog */}
      <DeleteDialog
        open={showDeleteDialog}
        name={runbook.name}
        deleting={deleteMutation.isPending}
        onClose={() => setShowDeleteDialog(false)}
        onConfirm={() => deleteMutation.mutate()}
      />
    </div>
  );
}
